【问题标题】:Sending EPPLus Excel file via HttpContext通过 HttpContext 发送 EPPLus Excel 文件
【发布时间】:2021-05-31 10:17:48
【问题描述】:

我正在为我的 .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 文件吗?

【问题讨论】:

  • 您为什么要写入 HttpContetxt.Response 而不是返回 ActionResult,例如使用 return File() ?至于哪里出了问题,错误非常清楚。您尝试使用一种类型与期望完全不同的语气的方法
  • 我不熟悉 return File(),我想使用上下文,以便我可以立即将文件下载到客户端的 PC。我现在明白我的错误了,尽管欢呼

标签: c# asp.net-core epplus httpcontext


【解决方案1】:

折腾了一下,看来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;
        }
    }

【讨论】:

  • 有几个重复的问题表明了这一点。此外,所有控制器动作都应该返回一个 IActionResult。为什么要尝试直接写入响应?
  • write to the Response directly?是什么意思
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多