一、使用NPOI导出Excel
//引入NPOI包
- HTML
<input type="button" class="layui-btn layui-btn-blue2 layui-btn-sm" id="ExportExcel" onclick="ExportExcel()" value="导出" />
- JS
//导出Excel
function ExportExcel() {
window.location.href = "@Url.Action("ExportFile")";
}
- C#
private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;
public HomeController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpGet("ExportFile")]
//导出文件
public async Task<IActionResult> ExportFile()
{
//获取数据库数据
var result = await _AnsweringQuestion.GetTeacherName();
string filePath = "";
//获取文件路径和名称
var wwwroot = _hostingEnvironment.WebRootPath;
var filename = "Table.xlsx";
filePath = Path.Combine(wwwroot, filename);
//创建一个工作簿和工作表
NPOI.XSSF.UserModel.XSSFWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
var sheet = book.CreateSheet();
//创建表头行
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("姓名");
headerRow.CreateCell(1).SetCellValue("科目");
headerRow.CreateCell(2).SetCellValue("说明");
//创建数据行
var data = result.DataList;
for (int i = 0; i < data.Count(); i++)
{
var dataRow = sheet.CreateRow(i + 1);
dataRow.CreateCell(0).SetCellValue(data[i].TeacherName);
dataRow.CreateCell(1).SetCellValue(data[i].TeachSubject);
dataRow.CreateCell(2).SetCellValue(data[i].TeacherDesc);
}
//将Execel 文件写入磁盘
using (var f = System.IO.File.OpenWrite(filePath))
{
book.Write(f);
}
//将Excel 文件作为下载返回给客户端
var bytes = System.IO.File.ReadAllBytes(filePath);
return File(bytes, "application/octet-stream", $"{System.DateTime.Now.ToString("yyyyMMdd")}.xlsx");
}