通过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;
}
}

相关内容

  • 没有找到相关文章

最新更新