Export array of JSON objects to Excel using SheetJS

Mavericks picture Mavericks · Aug 24, 2018 · Viewed 11.7k times · Source

I have an array of JSON objects, like this:

[
  {"name":"John", "city": "Seattle"},
  {"name":"Mike", "city": "Los Angeles"},
  {"name":"Zach", "city": "New York"}
]

when I use the code below, it's not working:

     _export: function(records,opts) {
                    var XLSX = xlsx;
                    var fileName = opts.split(".")[2]
                    var workSheet = XLSX.utils.json_to_sheet(records);
                    console.log("THis is Worksheet",workSheet);
                    var wb = XLSX.utils.book_new();
                    console.log("THis is workbook",wb)
                    XLSX.utils.book_append_sheet(wb, workSheet, fileName);
                    
                    var bin = XLSX.write(wb, {bookType:'xlsx',type: "binary"});
                    return new Blob([this._binStr2ArrBuff(bin)], { type: "" });
                },
            },

I'm using SheetJS version 0.9.11, just wanted to check if there is any way to export it into Excel format? I'm stuck here for the last 2 days. Any help would be highly appreciated.

Answer

NullPointer picture NullPointer · Aug 24, 2018

I think you have to use XLSX.writeFile(wb, 'book.xlsx') for export Excel file.

Replace this code:

var bin = XLSX.write(wb, {bookType:'xlsx',type: "binary"});
return new Blob([this._binStr2ArrBuff(bin)], { type: "" });

Here is the reference:https://lovemewithoutall.github.io/it/json-to-excel/