1.建立好Excel导出数据要用到的模板 T.xlsx
2.引入程序包
3.将读取出来的数据List放到Excel中
public async Task<IActionResult> GetExcel(){
var dt = DateTime.Now;
var rootPath = _webHostEnvironment.ContentRootPath + "/Template/";
if (Directory.Exists(rootPath) == false)
Directory.CreateDirectory(rootPath);
var templateFile = rootPath + "T.xlsx";
if (listView.Count == 0)
{
return Ok(new ReturnMessage()
{
IsSuccess = false,
ResultCode = "100002",
Message = "无数据"
});
}
var memory = new MemoryStream();
using (var fs = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = new XSSFWorkbook(fs);
var sheet = workbook.GetSheetAt(0);
sheet.DisplayGridlines = true;
var rowIndex = 2;
foreach (var item in listView)
{
var datarow = sheet.CreateRow(rowIndex);
datarow.CreateCell(0).SetCellValue(item.数据1);
datarow.CreateCell(1).SetCellValue(item.数据2);
datarow.CreateCell(2).SetCellValue(item.数据3);
rowIndex++;
}
var datarowTotalPrice = sheet.CreateRow(rowIndex);
workbook.Write(memory);
}
memory.Position = 0;
var fileName = "导出文件名_" + dt.Date.ToString("yyyy-MM-dd") + ".xlsx";
return File(memory, "application/vnd.ms-excel", fileName);
}