close

How to save .xlsx data to file as a blob

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to save .xlsx data to file as a blob in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to save .xlsx data to file as a blob ?

  1. How to save .xlsx data to file as a blob ?

    to save .xlsx data to file as a blob This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx
    /* generate array buffer */ var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'}); /* create data URL */ var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'})); /* trigger download with chrome API */ chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

  2. How to save .xlsx data to file as a blob ?

    to save .xlsx data to file as a blob This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx
    /* generate array buffer */ var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'}); /* create data URL */ var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'})); /* trigger download with chrome API */ chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

Method 1

Here’s my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.

return fetch(fullUrlEndpoint, options)
  .then((res) => {
    if (!res.ok) {
      const responseStatusText = res.statusText
      const errorMessage = `${responseStatusText}`
      throw new Error(errorMessage);
    }
    return res.arrayBuffer();
  })
    .then((ab) => {
      // BE endpoint sends a readable stream of bytes
      const byteArray = new Uint8Array(ab);
      const a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(
        new Blob([byteArray], {
          type:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        }),
      );
      a.download = `${fileName}.XLSX`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch(error => {
      throw new Error('Error occurred:' + error);
    });

Method 2

This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment