XLSX.utils.book_new()不是函数错误

时间:2019-02-21 06:57:58

标签: javascript jquery filesaver.js sheetjs

我正在使用SheetJS库将Excel转换为JSON,反之亦然。虽然将Excel转换为JSON的代码工作正常,但是将JSON转换回Excel的代码却存在问题。请在下面找到代码:

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');

上面的代码不断给出XLSX.utils.book_new()不是函数错误。有人遇到过类似的问题吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。这是因为找不到相对路径,因此无法调用XLSX.utils.book_new。您可以这样使用源代码的绝对路径:

<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>