Webapi export to export damaged file

I used OfficeOpenXml ExcelPackage to generate excel from a list of objects. This loads the file successfully, however, when I open the excel file, it complains that it is damaged and is not saved in the correct file format. I also tried using FIleSaver.js but no luck with this. The same mistake. Any suggestions on how to fix this?

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

When I open Excel, I get an error because "Excel found unreadable content in Products.xlsx. You want to change the contents of this book .......".

I checked the API response and saw that WebApi returns some data in OfficeOpenML format, not sure if this is a problem

Please help me in solving this problem. Found a similar problem that has not been resolved.

+5
source share

Source: https://habr.com/ru/post/1234148/


All Articles