//新的Excel寫法#2
//新的Excel寫法#2
public Task<string> CommonWriteExcel<TData>(List<TData> dataList,Dictionary<string,string>reportHeader)
{
var dataObject = JsonConvert.SerializeObject(dataList);
DataTable table = JsonConvert.DeserializeObject<DataTable>(dataObject);
using( var ms = new MemoryStream())
{
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Sheet1");
List<String> columns = new List<string>();
IRow row = excelSheet.CreateRow(0);
int columnIndex = 0;
foreach (System.Data.DataColumn column in table.Columns)
{
if (reportHeader.Keys.Contains(column.ColumnName))
{
columns.Add(column.ColumnName);
row.CreateCell(columnIndex).SetCellValue(reportHeader[column.ColumnName]);
columnIndex++;
}
}
int rowIndex = 1;
foreach (DataRow dsrow in table.Rows)
{
row = excelSheet.CreateRow(rowIndex);
int cellIndex = 0;
foreach (String col in columns)
{
row.CreateCell(cellIndex).SetCellValue(dsrow[col].ToString());
cellIndex++;
}
rowIndex++;
}
workbook.Write(ms);
return Task.FromResult(Convert.ToBase64String(ms.ToArray()));
}
}
留言
張貼留言