I utilized OfficeOpenXml ExcelPackage to create an excel file from a list of Objects. The download is successful, but upon opening the file, Excel issues a warning that it is corrupted and not saved in the proper file format. I also attempted using FileSaver.js with no success - encountering the same error. Any suggestions on how to resolve this issue?
Server-Side Code:
ExcelPackage _excelPackage = new ExcelPackage();
ExcelWorksheet _sheet = _excelPackage.Workbook.Worksheets.Add("New Sheet");
int currentRow = 1;
foreach (var prod in Products)
{
_sheet.Cells[currentRow, 0].Value = prod.Id;
_sheet.Cells[currentRow, 0].Value = prod.Name;
_sheet.Cells[currentRow, 0].Value = prod.Price;
currentRow++;
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
byte[] stream = _excelPackage.GetAsByteArray()
response.Content = new ByteArrayContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Products.xlsx"
};
return response;
Client-Side (AngularJS Service Code):
var req = {
url: fpReportsWebAPIURL + 'api/Export/DownloadFile',
method: 'POST',
responseType: 'arraybuffer',
//data: json, //this is your json data string
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
};
return $http(req).then(function (data) {
var type = data.headers('Content-Type');
var blob = new Blob([data], {
type: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
});
saveAs(blob, 'Products' + '.xlsx');
return true;
});
Upon opening the Excel, I receive the error message "Excel found unreadable content in Products.xlsx. Do you want to recover the contents of this workbook...".
After inspecting the API response, I noticed that WebApi returns some data in OfficeOpenML format, unsure if this may be causing the issue.
Please assist me in resolving this problem as a similar issue encountered was left unanswered.