简体   繁体   中英

Having trouble saving Excel spreadsheet from asp.net web api backend using Aspose.Cells, and Angular 2 front end

On my ASP.NET web api backend I have Aspose.Cells make a spreadsheet. I have been saving it locally and the spreadsheet is good, but now that I am trying to host it on a server I have to send the spreadsheet through the HTTP response. At the end of my web api route I have the following code:

workbook.Save(HttpContext.Current.Response, output.xls, ContentDisposition.Inline, new XlsSaveOptions());
HttpContext.Current.Response.End();

This sends the response which can be seen here in Chrome dev tools: 在此处输入图片说明

As you can see, the body is just random gibberish mostly which I'm assuming is just binary. On the client my typescript inside the subscribe method which receives the response looks like this:

var blob = new Blob([data._body], { type: 'application/vnd.ms-excel' });
        var url = window.URL.createObjectURL(blob);
        window.open(url);

This saves the file with a name like f811c3bc-2eea-4394-b463-93c61ccc7677.xls, and inside the spreadsheet it again just looks like gibberish, after excel warns me that the file is a different format than the extension:
在此处输入图片说明

The words 'detail' and 'site detail' are words that should be in there, so at least something that I want shows up, but its obviously not quite there. What am I doing wrong? This is supposed to be a spreadsheet with 20+ tabs and up to a couple thousand rows on a few of the tabs, and less than 10 on others.

EDIT: I have fixed my problem for anyone searching from the future. On your HTTP request options, you need to set the response type to ArrayBuffer. I also switched to using Filesaver.js although I'm not sure if that is actually needed or not.

We are afraid, Web Browsers don't understand XLS (Excel 2003) and XLSX (Excel 2007 and newer) format. Only Microsoft Excel understands it. It means, you cannot show your Excel files in Web Browsers. You can just ask the user to download them and then users will have to open them in their Microsoft Excel application on their own.

However, some of the browsers understands (or they have plug-ins) Pdf format . If you want to show your Excel file contents, then render it to Pdf using Aspose.Cells and then user will be able to view it inline if he is using Google Chrome, FireFox etc.

Anyhow, you will have to send it as attachment. Please change your code like this.

workbook.Save(HttpContext.Current.Response, output.xls,ContentDisposition.Attachment, new XlsSaveOptions());
HttpContext.Current.Response.End();

Note: I am working as Developer Evangelist at Aspose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM