Node.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.sr > R) range.sr = R; if(range.sc > C) range.sc = C; if(range.er < R) range.er = R; if(range.ec < C) range.ec = 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.sc < 10000000) workSheet['!ref'] = xlsx.utils.encode_range(range); return workSheet; } } 

这是解决scheme:

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

你也可以使用下面的方法:

 var FileSaver = require('file-saver') /* add worksheet to workbook */ wb.SheetNames[0] = 'Testing'; wb.Sheets['Testing'] = ws; //worksheet handle var wopts = { bookType:'xlsx', bookSST:false, type:'binary'}; var wbout = XLSX.write(wb,wopts); /* the saveAs call downloads a file on the local machine */ FileSaver.saveAs(new Blob([s2ab(wbout)],{type: ""}), "test.xlsx")