1. 程式人生 > >匯出excel通用介面

匯出excel通用介面

public static MemoryStream ExportToMemoryStream(List wechatlogList)
{
XSSFWorkbook book;
ISheet currentSheet;
string templateFilePath = HttpContext.Current.Server.MapPath("~/App_Data/Template/WechatLog.xlsx");
if (System.IO.File.Exists(templateFilePath))
{
using (FileStream file = new FileStream(templateFilePath, FileMode.Open, FileAccess.Read))
{
book = new XSSFWorkbook(file);
currentSheet = book.GetSheet(“Sheet1”);
file.Close();
}
}
else
{
book = new XSSFWorkbook();
currentSheet = book.CreateSheet(“Sheet1”);
}
Type type = typeof(T);

var columns = type.GetProperties().Select(t => t.Name).ToList();
var headers = type.GetProperties().Select(t =>
{
var header = t.Name;
var orderAt = columns.IndexOf(header);
return new ExcelData[]
{
new ExcelData()
{
Value = header,
Index = orderAt
}
};
}).SelectMany(t => t);
var bodyRows = wechatlogList.Select(element => type.GetProperties().Select(member =>
{
var row = member.GetValue(element);
var orderAt = columns.IndexOf(

member.Name);
return new ExcelData[]
{
new ExcelData()
{
Value = row.NullToString(),
Index = orderAt
}
};
}).SelectMany(t => t));

IRow headerRow = currentSheet.CreateRow(0);
headers.OrderBy(p => p.Index).ForEach((v, i) =>
{
headerRow.CreateCell(i).SetCellValue(v.Value);
});
bodyRows.ForEach((bodyRow, bodyRowIndex) =>
{
IRow currentBodyRow = currentSheet.AppendRow();
bodyRow.OrderBy(p => p.Index).ForEach((v, i) =>
{
currentBodyRow.CreateCell(i).SetCellValue(v.Value);
});
});
MemoryStream ms = new MemoryStream();
book.Write(ms);
return ms;
}