MemoryStream生成Excel

public static MemoryStream ToExcel<T>(List<T> list, string filePath = null)
{
var memoryStream = new MemoryStream();
 

IWorkbook workbook = new HSSFWorkbook();
string sheetName = typeof(T).Name;
ISheet sheet = workbook.CreateSheet(sheetName);
IRow headerRow = sheet.CreateRow(0);
Type elementType = typeof(T);
// handling header.

int headerIndex = 0;
elementType.GetProperties().ToList().ForEach(propInfo =>
{
ICell headerCell = headerRow.CreateCell(headerIndex);
headerIndex = headerIndex + 1;
headerCell.SetCellValue(propInfo.Name);


});
int rowIndex = 1;
foreach (T item in list)
{
IRow dataRow = sheet.CreateRow(rowIndex);
int rowcellIndex = 0;
elementType.GetProperties().ToList().ForEach(propInfo =>
{
ICell cell = dataRow.CreateCell(rowcellIndex);

string value = (propInfo.GetValue(item, null) ?? "").ToString();
cell.SetCellValue(value);
rowcellIndex++;
});
rowIndex++;
}


///storage/emulated/0/DCIM
//FileStream fs = new FileStream("/storage/emulated/0/DCIM/log.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite);

workbook.Write(memoryStream);

//fs.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
 
//fs.Dispose();
workbook = null;

return memoryStream;
 

}
原文地址:https://www.cnblogs.com/zengwangjing/p/net.html