正在下载 Excel 个文件

Downloading Excel File

我之前问过这个问题,但在启动文件下载时仍然遇到困难。

var fileName = "ExcelData.xlsx";
var file = new FileInfo(fileName);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
   var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Employee Data");
   if (package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Employee Data") == null)
   {
       worksheet = package.Workbook.Worksheets.Add("Employee Data");
   }
   else
   {
       package.Workbook.Worksheets.Delete(1);
       worksheet = package.Workbook.Worksheets.Add("Employee Data");
    }
     worksheet.Cells[1, 1].Value = "Date start";
     worksheet.Cells[1, 2].Value = "Name";

     var rowCounter = 2;
      foreach (var v in users)
      {
         string dt = v.DateAdded.ToString();
         worksheet.Cells[rowCounter, 1].Value = dt;
         worksheet.Cells[rowCounter, 2].Value = v.Name;
         rowCounter++;
      }
      package.Workbook.Properties.Title = "Employee Data";

      System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
      response.Clear();
      response.Buffer = true;
      response.Charset = "";
      response.ContentType = "application/vnd.openxmlformats-     officedocument.spreadsheetml.sheet";
      response.AddHeader("content-disposition", "attachment;filename=ExcelData.xlsx");
      response.BinaryWrite(package.GetAsByteArray());
}

目前没有错误发生,但也没有触发下载。如何触发下载以便将生成的文件保存到默认下载文件夹

尝试输入您的代码:

Response.Flush();
Response.Close();
Response.End();

它立即输出结果。

你为什么不return一个FileContentResult

由于您使用的 Excel 库可以 return 将 sheet 作为字节数组,因此这对您有用。

在您的控制器中,您可以像这样 return FileContentResult

return File(package.GetAsByteArray(), "application/xlsx", "YourReportName.xlsx");

所以你可以从你的代码中删除这个块:

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
  response.Clear();
  response.Buffer = true;
  response.Charset = "";
  response.ContentType = "application/vnd.openxmlformats-     officedocument.spreadsheetml.sheet";
  response.AddHeader("content-disposition", "attachment;filename=ExcelData.xlsx");
  response.BinaryWrite(package.GetAsByteArray());

只是 return 文件,如上所示。

请注意,您必须为 System.Web.Mvc.

添加一个 using 语句到您的控制器