Phoenix Dev
Phoenix Dev

Reputation: 457

Download an excel(.xlsx) file using blob in angular 2

How to download an .xlsx file saved in a angular 2 project folder from a browser using blob. I am able to download a csv by using the following code:

return this.http.get(fileUrl, {headers: headerInfo})
    .map((response: any) => {
        return new Blob([response._body], {type: 'text/csv'});
    });

Any help would be appreciated! Thanks!

Upvotes: 0

Views: 3454

Answers (1)

Michael Johansen
Michael Johansen

Reputation: 5106

You could probably just use fetch and file-saver to retrieve the Excel file:

import { saveAs } from 'file-saver';

// Client side.
// Note: it helps it server serves the appropriate response header, like e.g.
// 'Content-Type': 'application/vnd.openxmlformats'

return fetch(excelFileUrl, { headers: headerInfo })
  .then(res => res.blob()) // extract binary blob from response
  .then(blob => {
    // Download blob with file-saver
    FileSaver.saveAs(blob, "MyFile.xlsx");
  })
  .catch((err) => { console.error('Excel download failed', err); });

Upvotes: 1

Related Questions