Node.js -保存xlsx到磁盘
Node.js - save xlsx to disk
我使用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 */
您还可以使用以下方法:
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")
相关文章:
- 如何在读取XLS/XLSX本地文件时,使用IE的javascript代码启用未标记为安全的ActiveX控件
- Excellen导出xlsx支持
- Javascript-将每个传入的数据直接保存到磁盘
- Office 365-创建*.docx|*.pptx|*.xlsx文件
- 在javascript中导入xlsx文件时,如何手动强制javascript事件
- 将从浏览器创建的文件保存到磁盘 - 不能在 Firefox 上使用新的 File()
- 获取图像's磁盘中文件的实际高度和宽度
- 如何使用JavaScript在Internet Explorer中将文件(DOCX或XLSX或PNG)读取为二进制流
- 将json写入本地磁盘javascript
- 使用javascript从磁盘中的文件夹中选择所有图像的路径
- Outlook加载项使用Javascript将附件保存到磁盘
- 如何从本地文件夹(磁盘存储)读取或获取图像文件,并使用nodejs服务器将其发送到Angularjs
- 流星js如何从服务器向磁盘写入文件
- Javascript错误:磁盘已满
- PHP:如何用unicode字符将文件写入磁盘
- 从php中的本地磁盘读取文件
- BIRT报告在设计模式下导出到XLSX,但在运行时不导出
- 如何在JSF中将toDataURL方法返回的画布内容作为图像存储在磁盘上
- JavaScript-从本地磁盘打开一个文件
- Node.js -保存xlsx到磁盘