Downloading Excel File
18,521
Solution 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
.
Solution 2
Try after your code:
Response.Flush();
Response.Close();
Response.End();
It immediately outputs the result.
Author by
Arianule
Updated on June 04, 2022Comments
-
Arianule almost 2 years
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
-
Pankaj Kapare over 9 yearsTry commenting out response.Clear(); line.
-