先通过NuGet安装NPIO框架组件。
[HttpGet("export")] public FileResult Export() { HSSFWorkbook book = new HSSFWorkbook(); ISheet sheet = book.CreateSheet("Sheet1"); int cellIndex = 0; var row = sheet.CreateRow(0); row.CreateCell(cellIndex++).SetCellValue("列1"); row.CreateCell(cellIndex++).SetCellValue("列2"); int rowIndex = 1; var result = GetDataSource();//数据通过Dapper查询,返回dynamic类型 foreach (var item in result.Item1) { cellIndex = 0; row = sheet.CreateRow(rowIndex); row.CreateCell(cellIndex++).SetCellValue("列1值"); row.CreateCell(cellIndex++).SetCellValue("列2值"); rowIndex++; } using (MemoryStream ms = new MemoryStream()) { book.Write(ms); ms.Seek(0, SeekOrigin.Begin); return File(ms.ToArray(), "application/vnd.ms-excel", $"{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls"); } } dynamic GetDataSource() { return new object(); }