如何在节点中使用xslx库写入csv?

时间:2018-06-12 13:37:10

标签: node.js

我必须将其中一张工作表从xslx转换为csv,因为我使用以下代码:

url = 'routes/file.xlsx';
const workbook = XLSX.readFile(url); 
const csv = XLSX.utils.sheet_to_csv(workbook.Sheets.files);
XLSX.writeFile(csv, 'file.csv');

但是当我执行它时,我得到了那个错误,知道该怎么做。

谢谢

1 个答案:

答案 0 :(得分:0)

首先生成您的CSV内容:

var table = document.getElementById(id);
var wb = XLSX.utils.table_to_book(table, { sheet: "Sheet JS" });
var ws1 = wb.Sheets[wb.SheetNames[0]];
var csv = XLSX.utils.sheet_to_csv(ws1, { strip: true });
download_file(csv, 'my_csv.csv', 'text/csv;encoding:utf-8');

然后将download_file函数记入Javascript: set filename to be downloaded

 function download_file(content, fileName, mimeType) {
        var a = document.createElement('a');
        mimeType = mimeType || 'application/octet-stream';

        if (navigator.msSaveBlob) { // IE10
            navigator.msSaveBlob(new Blob([content], {
                type: mimeType
            }), fileName);
        } else if (URL && 'download' in a) { //html5 A[download]
            a.href = URL.createObjectURL(new Blob([content], {
                type: mimeType
            }));
            a.setAttribute('download', fileName);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        } else {
            location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
        }
    }