I am trying to download an excel file with large data set. On server side I am using EPPlus library to generate excel. I then pass the stream obj to client side. Client side code download the excel file using that stream obj.
When I open the downloaded file I get corrupt file error message. Where I am going wrong?
Server side code (C#)
public async Task<IActionResult> DownloadExcel(Model postData)
{
string apiUrl = "Api/URL/Get";
apiUrl += "?Status=" + postData.Status +
"&Gender=" + postData.Gender +
"&CurrentAge=" + postData.CurrentAge;
var result = await CallAPI.GetListFromApiAsync<ResultModel>(apiUrl);
var stream = new MemoryStream();
using (ExcelPackage excel = new ExcelPackage(stream))
{
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
// Column
workSheet.Cells[1, 1].Value = "Column 1";
workSheet.Cells[1, 2].Value = "Column 2";
.
.
.
workSheet.Cells[1, 19].Value = "Column 19";
// Row
int recordIndex = 2;
foreach (var d in result)
{
workSheet.Cells[recordIndex, 1].Value = d.data1;
workSheet.Cells[recordIndex, 2].Value = d.data2;
.
.
.
workSheet.Cells[recordIndex, 19].Value = d.data4;
recordIndex++;
}
for (int i = 1; i < 20; i++)
{
workSheet.Column(i).AutoFit();
}
string fileName = @"download.xlsx";
string fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, fileType, fileName);
}
}
Client side ajax call
$.ajax({
url: "/SomeURL/DownloadExcel",
type: "POST",
data: form.serialize(),
success: function (result) {
var binaryData = [];
binaryData.push(result);
var blob = new Blob([binaryData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'download.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});