Search code examples
excelbrowserblobfilesaver.jsjs-xlsx

How to open a Blob object in the browser?


I currently have a blob object which I would like to give the user the option to open.

I am currently using js-xlsx from the SheetsJS library. I have successfully created an excel sheet with the given data I need in it.

I convert the excel sheet object into a Blob and use FileSaver.js to successfully give the user the option to save the excel sheet.

saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}), 'mysheet.xlsx');

function s2ab(s: any) {
   var buf = new ArrayBuffer(s.length);
   var view = new Uint8Array(buf);
   for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
   return buf;            
}

Here is the whole function:

exportExcel() {
  var wb = XLSX.utils.book_new();
  wb.Props = {
          Title: "SheetJS",
          Subject: "CCDB",
          Author: "CCDB",
          CreatedDate: new Date(2017,12,19)
  };

  wb.SheetNames.push("Test Sheet");
  var ws_data = this.slotData;
  ws_data.unshift(this.headers);
  ws_data.unshift(['Slots :: CCDB']);
  var ws = XLSX.utils.aoa_to_sheet(ws_data);
  var wscols = [
    {wch:8},
    {wch:25},
    {wch:25},
    {wch:15},
    {wch: 10},
    {wch: 10},
    {wch: 35},
    {},
    {}
  ];
  ws['!cols'] = wscols;
  ws['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 8 } }];
  // XLSX.utils.
  wb.Sheets["Test Sheet"] = ws;
  var wbout = XLSX.write(wb, {bookType: 'xlsx',  type: 'binary'});
  function s2ab(s: any) {

          var buf = new ArrayBuffer(s.length);
          var view = new Uint8Array(buf);
          for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;

  }
  saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}), 'Slots CCDB.xlsx');
},

The file saves correctly, but it is not exactly the dialogue box I want.

I want to give the user the option to OPEN the file, ie. "in Excel", like this:

enter image description here

I am currently able to open a CSV file like this, by converting the data into a url and passing it into window.open().

exportCSV() {
  let csv = 'data:text/csv;charset=utf-8,';
  const csvContent = Papa.unparse({
    fields: this.headers,
    data: this.slotData,
  });
  csv += csvContent;
  const encodedUri = encodeURI(csv);
  window.open(encodedUri);
},

I just can't seem to get this to work with a .xlsx file though.

Anyone have any ideas?


Solution

  • Okay, I have figured it out.

    Turns our I just had to change the type to 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' to be opened from a blob as a .xlsx file!

          saveAs(new Blob([s2ab(wbout)], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          }), 'Slots CCDB.xlsx');