背景:
在前端无法生成特殊的excel表格,或操作复杂的时候会通过后台进行生成excel。但是服务器的资源也非常宝贵,所以通过数据流的方式就可以实现:不在服务器存储的情况下,使前端成功下载excel文件;
效果如下:
代码如下:
1,封装的方法:
/// <summary> /// 导出excel模板 /// </summary> /// <returns></returns> public static byte[] OutputExcel() { try { NPOI.SS.UserModel.IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("sheet"); IRow Title = sheet.CreateRow(0); for (int i = 0; i < 51; i++) { Title.CreateCell(i).SetCellValue("title" + i); } byte[] buffer = new byte[1024 * 5]; using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms, false); //ms.Flush(); //ms.Position=0; buffer = ms.ToArray(); ms.Close(); } return buffer; } catch (Exception ex) { return null; } }
2,控制器方法:
[HttpGet(Name = "Test")] public FileResult Test() { var result = ExcelHelper.OutputExcel(); return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "UploadTemplate.xlsx"); }
标签:webApi,sheet,Excel,excel,ms,数据流,return From: https://www.cnblogs.com/BFMC/p/17025420.html