由C#后台导出,Nuget 搜索 NPOI 后引用, 用于处理和生成Excel。
代码:
public static void DataTableExcel(DataTable dataTable, string fileName, string sheetName)
{
IWorkbook workBook = new XSSFWorkbook();
ISheet sheet = workBook.CreateSheet(sheetName);
IRow header = sheet.CreateRow(0);
for (int i = 0; i < dataTable.Columns.Count; i++)
{
ICell cell = header.CreateCell(i);
cell.SetCellValue(dataTable.Columns[i].ColumnName);
}
for (int i = 0; i < dataTable.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
}
//转为字节数组
MemoryStream stream = new MemoryStream();
workBook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
stream.Dispose();
}
}