Download the Excel file from the server and save it on the client

I have a JavaScript application and an API that creates an Excel file and returns an array of bytes with the following headers:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Content-Disposition:attachment; filename=List.xlsx 

When I go to the Excel Resource API URL, I am prompted to download the Excel file. If I do this, it will load fine and open in Excel. Things are good.

Now to the problem:

I do not want to show the API URL in the user's browser window, so my goal is:

  • Download Excel file via AJAX XMLHttpRequest
  • Store the contents (byte array) in a block
  • Create Data URIs Using Blob
  • Open the data URI in a popup window that prompts the user to download the Excel file.

What I have:

It downloads the file, but when I try to open the file, Excel does not recognize it as a valid Excel file.

 // "data" is the contents from the server var reader = new FileReader(); var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); reader.readAsDataURL(blob); reader.onloadend = function (e) { window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank'); } 
+8
javascript excel blob filereader
source share
1 answer

I have earned. I just had to add the following to my XMLHttpRequest object:

 responseType: 'arraybuffer' 

But this does not work in IE, because IE cannot open data URIs. Even IE11.

Anyway, I found a great library called FileSaver.js that handles files for all major browsers (including IE10 +)

+8
source share

All Articles