c# - 通过 HttpContext 发送 EPPLus Excel 文件
问题描述
我正在为我的 .NET Core 3.1 应用程序使用 EPPLus 库;目前我正在尝试实现一个简单的Export
功能,它根据给定的数据制作一张表格并立即将其下载到用户的 PC 上。
我有以下内容:
public void Export(ProductionLine productionLine, HttpContext context)
{
using (var package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("MySheet");
ws.Cells["A1"].Value = "This is cell A1";
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.Headers.Add(
"content-disposition",
string.Format("attachment; filename={0}", "MySheet.xlsx"));
context.Response.SendFileAsync(package);
}
}
HttpContext
是通过一个简单地调用 HttpContext 控制器基础的控制器给出的。HttpContext 是基于Microsoft.AspNetCore.Http
我目前遇到的错误是cannot convert from 'OfficeOpenXml.ExcelPackage' to 'Microsoft.Extensions.FileProviders.IFileInfo'
合乎逻辑的,但我相信将文件更改IFileInfo
为不可能。
还有另一种通过 HttpContextResponse 发送 EPPlus 文件的方法吗?
解决方案
摆弄了一下,似乎使用该return File()
功能更容易了。我已经Export
像这样重做了我的功能:
public object Export(ProductionLine productionLine, HttpContext context)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
FileInfo fileName = new FileInfo("ExcellData.xlsx");
using (var package = new OfficeOpenXml.ExcelPackage(fileName))
{
var ws = package.Workbook.Worksheets.Add("MySheet");
ws.Cells["A1"].Value = "This is cell A1";
MemoryStream result = new MemoryStream();
result.Position = 0;
package.SaveAs(result);
return result;
}
我的控制器是这样的:
public IActionResult ExportCSV([FromQuery] string Orderno)
{
try
{
ProductionLine prodLine = _Prodline_Service.GetAllByOrderno(Orderno);
MemoryStream result = (MemoryStream)_ExcelExportService.Export(prodLine, HttpContext);
// Set memorystream position; if we don't it'll fail
result.Position = 0;
return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} catch(Exception e)
{
Console.WriteLine(e);
return null;
}
}
推荐阅读
- javascript - JS 中的日期评估
- css - 如何修复相对于可滚动容器的 div?
- javascript - 用可用的元素和表单构建一个网格 Popper Js 和什么?
- javascript - 反应:在状态下访问数组时变得未定义
- javascript - React 方法返回值不会在 render() 中显示
- api - 杜比声称在 Interactivity API 下提供 Spatial Audio,但没有找到与此相关的文档
- c# - 视图中的动态标签,显示从另一个模型查询的信息
- javascript - Angular - 深层嵌套对象模型链接
- laravel - 目标类 [App\http\Controllers\FrontController] 不存在
- node.js - Gitlab 测试覆盖率可视化不起作用