javascript - Node.js - 将 xlsx 保存到磁盘

标签 javascript node.js express excel-2007 js-xlsx

我正在使用 Node.js 和 js-xlsx用于生成新的 Excel 文件。 生成新文件时,我希望将其保存到本地磁盘。

此代码用于生成和下载新的 Excel 文件,如何将其存储到磁盘?

FileManagement.generateExcelFile("xlsx-filtered-list", "error-sheet", finalResult, res);

generateExcelFile(fileName, sheetName, data, res) {
    const workSheet = sheet_from_array_of_arrays(data);
    const workBook = new Workbook();

    workBook.SheetNames.push(sheetName);
    workBook.Sheets[sheetName] = workSheet;

    const workBookOptions = { bookType:'xlsx', bookSST:false, type:'binary' };
    const workBookFile = xlsx.write(workBook, workBookOptions);

    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', 'attachment; filename='+fileName);
    res.end(workBookFile, 'binary');

    // Functions work Excel generation (don't touch)
    function Workbook() {
        if(!(this instanceof Workbook)) return new Workbook();
        this.SheetNames = [];
        this.Sheets = {};
    }

    function sheet_from_array_of_arrays(data) {
        const workSheet = {};
        const range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
        for(let R = 0; R != data.length; ++R) {
            for(let C = 0; C != data[R].length; ++C) {
                if(range.s.r > R) range.s.r = R;
                if(range.s.c > C) range.s.c = C;
                if(range.e.r < R) range.e.r = R;
                if(range.e.c < C) range.e.c = C;
                const cell = {v: data[R][C] };
                if(cell.v == null) continue;
                const cell_ref = xlsx.utils.encode_cell({c:C,r:R});

                if(typeof cell.v === 'number') cell.t = 'n';
                else if(typeof cell.v === 'boolean') cell.t = 'b';
                else if(cell.v instanceof Date) {
                    cell.t = 'n'; cell.z = xlsx.SSF._table[14];
                    cell.v = datenum(cell.v);
                }
                else cell.t = 's';

                workSheet[cell_ref] = cell;
            }
        }
        if(range.s.c < 10000000) workSheet['!ref'] = xlsx.utils.encode_range(range);

        return workSheet;
    }
}

最佳答案

解决方法如下:

/* output format determined by filename */
XLSX.writeFile(workbook, 'out.xlsx');
/* at this point, out.xlsx is a file that you can distribute */

关于javascript - Node.js - 将 xlsx 保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867059/

相关文章:

javascript - 验证错误mongodb,node.js和Express后端

javascript - 在 jQuery 中为论坛设置按钮格式

node.js - 将 Typescript 类发布为 npm 包

javascript - 语法错误: Unexpected token v in JSON at position 2

node.js - Node JS - Express JS - 类型错误 : Object #<Object> has no method 'compile'

node.js - Bot Emulator 连接到另一台计算机上的 Node.js 服务

javascript - API 返回数据,但在 undefined object 中。这是怎么回事?

javascript - 为什么在 Chrome 中存储到变量 "name"的数组会转换为字符串?

javascript - 在 Javascript 中,如何判断用户是否同时按下两个键?

javascript - 在数组中预加载图像(并等待它们下载)