1、项目的依赖项中添加NPOI的包
2、在需要使用的地方引用NPOI并使用NPOI将数据填入excel:
using NPOI.XSSF.UserModel; // XSSF用于创建office2007及以后使用的格式,HSSF则是这之前的格式 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; // 创建工作簿 var workbook = new HSSFWorkbook(); // 创建表 var sheet = workbook.CreateSheet("设备表"); // CreateFont:创建字体样式 var headFont = workbook.CreateFont(); headFont.IsBold = true; // CreateCellStyle:创建单元格样式 var headStyle = workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; headStyle.SetFont(headFont); // CreateRow:操作指定表的指定行。 var rowIndex = 0; var row = sheet.CreateRow(rowIndex); // CreateCell:为指定行添加指定列(单元格)。 var cell = row.CreateCell(0); // 为单元格赋予值和样式。此处为表头 cell.SetCellValue("姓名"); cell.CellStyle = headStyle; cell = row.CreateCell(1); cell.SetCellValue("年龄"); cell.CellStyle = headStyle; // 实际数据部分的单元格样式 var cellStyle = workbook.CreateCellStyle(); cellStyle.BorderRight = BorderStyle.Thin; // 循环输入内容数据 // (此处模拟有一个名为list的集合存储了数个有姓名和年龄的T对象) foreach(T t in list) { row = sheet.CreateRow(++rowIndex); cell = row.CreateCell(0); cell.SetCellValue(t.Name); cell.CellStyle = cellStyle; cell = row.CreateCell(1); cell.SetCellValue(t.Age); cell.CellStyle = cellStyle; } // bs用于存储文件数据的字节数组,一般给前端下载的文件都需要用这种方式传递 byte[] bs; // 导出内存流并通过内存流读取为byte[] using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); bs = ms.GetBuffer(); } // 返回给前端下载:File(存储文件数据的字节数组, 对应文件content-type, 文件名) return File(bs, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "excel2007文件.xlsx");
根据实际调整表头和内容数据,然后执行代码即可返回一个Excel文件。
3、前端接收这个文件只需要用浏览器打开对应地址即可:
// 假设调用上面那段代码的方法的地址是"/api/Home/Export" location.href="/api/Home/Export";
随后浏览器就会下载返回的文件,导出Excel就完成了。