1 安装EPPlus.core
2创建一个帮助类
public class ExcelHelper { /// <summary> /// 导出数据到execl /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dataList">数据</param> /// <param name="headers">表头</param> /// <returns></returns> public static MemoryStreamDto CreateDataToExcel<T>(List<T> dataList, List<string> headers) { string fileName = $"{Guid.NewGuid().ToString()}.xlsx"; //保存在内存里,小文件,大文件的话得另外想办法 var stream = new MemoryStream(); using (ExcelPackage package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1"); worksheet.Cells.LoadFromCollection(dataList, true); for (int i = 0; i < headers.Count; i++) { worksheet.Cells[1, i + 1].Value = headers[i]; } package.Save(); } stream.Position = 0; var memoryStreamDto = new MemoryStreamDto() //一个自定的Dto,需要传什么参数可以自行定义 { Stream = stream, FileName = fileName }; return memoryStreamDto; } }
服务器调用
var dataList = EntityList; //要导入到Execl中的数据 var headers = new List<string>() { "表头列名1", "表头列名2", "表头列名3", "表头列名4", "表头列名5" }; var memoryStreamDto = ExcelHelper.CreateExcelFromList(dataList, headers);
控制器调用
public async Task<IActionResult> ExportDataListToExecl() //与方法JsonResult不同,这里返回的是IActionResult {var result = _service.ExportDataListToExecl(); //服务器的方法 return File(result.Stream, "application/octet-stream", result.FileName); //返回文件流形式,调用这个接口时,直接下载execl }