SXSSF导出数据
它的基本思路是:当内存中的数据够了一定行数(构造函数可以设置)之后就先刷到硬盘中。但是,你也别就真把100W数据一次性读到内存中,应该根据总数分批加载到内存(比如从数据库读需要分页一样)。
首先需要添加nuget包 NPOI

image.png
public FileResult exprotexcel(DataTable dt,string searchkey) {
HSSFWorkbook excelBook = new HSSFWorkbook(); //创建工作簿Excel
NPOI.SS.UserModel.ISheet sheet1 = excelBook.CreateSheet("访问记录");//为工作簿创建工作表并命名
//编写工作表 (1)表头 (2)数据:listStudent
int num = 1;
if (!string.IsNullOrEmpty(searchkey)) {
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);//创建第一行
row1.CreateCell(0).SetCellValue(searchkey);
num = 2;
}
NPOI.SS.UserModel.IRow row2 = sheet1.CreateRow(num-1);//创建第一行
row2.CreateCell(0).SetCellValue("访问时间"); //创建其他列并赋值( 根据具体数据写代码...)
row2.CreateCell(1).SetCellValue("URL"); //创建其他列并赋值( 根据具体数据写代码...)
row2.CreateCell(2).SetCellValue("IP");
row2.CreateCell(3).SetCellValue("访问方式");
row2.CreateCell(4).SetCellValue("序列号");
row2.CreateCell(5).SetCellValue("设备名称");
row2.CreateCell(6).SetCellValue("客户名称");
row2.CreateCell(7).SetCellValue("地区");
row2.CreateCell(8).SetCellValue("来源");
for (int i = 0; i < dt.Rows.Count; i++)
{
//创建行( 根据具体数据写代码...)
NPOI.SS.UserModel.IRow rowTemp = sheet1.CreateRow(i + num);
rowTemp.CreateCell(0).SetCellValue(dt.Rows[i]["CreateTime"].ToString());
rowTemp.CreateCell(1).SetCellValue(dt.Rows[i]["SouecrUrl"].ToString());
rowTemp.CreateCell(2).SetCellValue(dt.Rows[i]["SourceIp"].ToString());
rowTemp.CreateCell(3).SetCellValue(dt.Rows[i]["AccessPage"].ToString());
rowTemp.CreateCell(4).SetCellValue(dt.Rows[i]["serialNumber"].ToString());
rowTemp.CreateCell(5).SetCellValue(dt.Rows[i]["EquipmentName"].ToString());
rowTemp.CreateCell(6).SetCellValue(dt.Rows[i]["CustomerName"].ToString());
rowTemp.CreateCell(7).SetCellValue(dt.Rows[i]["EquipmentAddress"].ToString());
rowTemp.CreateCell(8).SetCellValue(dt.Rows[i]["Site"].ToString());
}
var fileName = "访客记录" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + ".xls";//文件名
//将Excel表格转化为流,输出
MemoryStream bookStream = new MemoryStream();//创建文件流
excelBook.Write(bookStream); //文件写入流(向流中写入字节序列)
bookStream.Seek(0, SeekOrigin.Begin);//输出之前调用Seek,把0位置指定为开始位置
return File(bookStream, "application/vnd.ms-excel", fileName);//最后以文件形式返回
}

image.png