3

I am using SheetJS library to convert Excel to JSON and vice versa. While the code to convert Excel to JSON works fine, there are issues with the code to convert JSON back to Excel. Please find the code below:

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

wb.SheetNames.push("Test Sheet");
var ws_data = [['hello', 'world']];
var ws = XLSX.utils.aoa_to_sheet(ws_data);
wb.Sheets["Test Sheet"] = ws;
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
function s2ab(s) {

    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" }), 'test.xlsx');

The above code keeps giving XLSX.utils.book_new() is not a function error. Has anybody come across similar issue ?

Thanks

Ashy Ashcsi
  • 1,529
  • 7
  • 22
  • 54
  • Where are you getting `XLSX.utils.book_new()` from in the first place? Are you following a tutorial? Can you link to the relevant documentation? –  Feb 21 '19 at 07:01
  • Yes, I am following the tutorial mentioned here: https://redstapler.co/sheetjs-tutorial-create-xlsx/ – Ashy Ashcsi Feb 21 '19 at 07:04
  • Which script did you include? Because if I try, it works fine: https://jsfiddle.net/khrismuc/L0dwo9pq/ –  Feb 21 '19 at 08:30
  • @ChrisG, path to the js file does not even exist. It throws 404 file not found error. – Ashy Ashcsi Feb 22 '19 at 07:21
  • Right, I apparently forgot to save the change. Fixed now. –  Feb 22 '19 at 07:47
  • 1
    I've come across a similar issue but have not been able to figure it out. I'm getting the following message `Uncaught TypeError: Cannot read property 'book_new' of undefined`. Were you able to solve your issue? – nviens May 09 '19 at 22:33

1 Answers1

0

I ran into the same issue. It's because the relative path isn't found and therefore cannot call XLSX.utils.book_new. You can use an absolute path to the source code like so:

<script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.2/xlsx.full.min.js"></script>
<script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
JHaazez
  • 21
  • 1
  • 4