WebAPI-Excel
在SpringBoot中,我们可以是使用Apache POI轻松创建Excel文件并写入文件内容
在ASP.NETCore中,我们也有多种操作Excel表格的方式
- OpenXML SDK 是最底层的技术,提供对 Office Open XML 文件的最大灵活性和控制力,但同时也增加了复杂性。
- EPPlus 在 OpenXML SDK 的基础上进行了抽象,提供了一套更易用的 API 来处理 Excel 文件,同时保持了良好的性能。
- ClosedXML 则是在 EPPlus 的基础上进一步简化了 API,特别注重于提高开发效率和用户体验,适用于那些希望快速实现功能而不需要深入了解底层细节的开发者。
Template
可以为 ClosedXML 提供一个 Excel 模板文件,然后使用该模板来生成新的报表。这种方法不仅可以保留模板中的格式、图表和其他静态内容,还可以动态填充数据,从而创建一致且专业的报表
Closed XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public byte[] ExportData() { string templatePath = Path.Combine(_webHostEnvironment.WebRootPath, "Resources", "运营数据报表模板.xlsx");
if (!File.Exists(templatePath)) { throw new FileNotFoundException("缺少模板文件", templatePath); }
byte[] templateBytes = File.ReadAllBytes(templatePath);
using (var stream = new MemoryStream()) { stream.Write(templateBytes, 0, templateBytes.Length); stream.Position = 0;
using (var workbook = new XLWorkbook(stream)) { IXLWorksheet worksheet = workbook.Worksheet("Sheet1");
stream.Position = 0; workbook.SaveAs(stream);
return stream.ToArray(); } } }
|
Controller的返回格式
在 ASP.NET Core 中,如果你不使用 IActionResult 或其派生类作为控制器方法的返回类型,默认情况下,ASP.NET Core 会尝试根据返回的对象类型选择适当的格式化程序来序列化响应。对于大多数对象,默认的行为是将它们序列化为 JSON,并设置 Content-Type 响应头为 application/json。
在ASP.NETCore中,无需同SpringBoot一样在Controller获取到response对象后响应文件内容
它提供了更加便捷的响应文件的方式:
返回内存中的文件
1 2 3 4 5 6 7
| public FileResult DownloadFile() { byte[] fileBytes = GetFileBytes();
return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ExportedFile.xlsx"); }
|
返回本地文件
1 2 3 4 5 6 7 8 9 10 11
| public FileResult DownloadPhysicalFile() { string filePath = Path.Combine(_env.WebRootPath, "excelTemplates", "Template.xlsx");
if (!System.IO.File.Exists(filePath)) { return NotFound(); }
return PhysicalFile(filePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Template.xlsx"); }
|
WebAPI静态文件的存放位置
我们通常将静态文件存放到启动项目中,然后通过注入IWebHostEnvironment对象来获取运行时的项目根路径,通过路径拼接就能读到我们想要的静态文件了
1 2 3 4 5 6 7 8
| private readonly IWebHostEnvironment _webHostEnvironment;
public ReportService(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; }
Path.Combine(_webHostEnvironment.ContentRootPath, "Resources", "运营数据报表模板.xlsx")
|