Downloading Excel File

可紊 提交于 2019-12-05 01:42:51

问题


I have asked this before but am still having difficulties in initiating the file download.

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());
}

As it is at the moment no errors occur but the download is also not triggered. How do I trigger the download so that the generated file is saved to a default download folder


回答1:


Why don't you return a FileContentResult?

Since the Excel library you are using can return the sheet as a byte array, this could work for you.

In your controller, you can just return the FileContentResult like this:

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

So you can remove this block from you code:

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());

and just return the File as shown above.

Just note you have to add a using statement to your controller for System.Web.Mvc.




回答2:


Try after your code:

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

It immediately outputs the result.



来源:https://stackoverflow.com/questions/28066181/downloading-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!