Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading Excel File

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

like image 351
Arianule Avatar asked Feb 12 '23 03:02

Arianule


2 Answers

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.

like image 132
Shadowind Avatar answered Feb 13 '23 19:02

Shadowind


Try after your code:

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

It immediately outputs the result.

like image 27
Andrei Olaru Avatar answered Feb 13 '23 20:02

Andrei Olaru