node使用xlsx导入导出excel
1.安装和引入xlsx
安装 npm install xlsx
引入:let xlsx = require('xlsx');
2.读取excel数据
function readFile(file) {
let f = file.raw;
let reader = new FileReader();
reader.readAsBinaryString(f);
reader.onload = function (e) {
let data = e.target.result;
let wb = xlsx.read(data, { type: 'binary' });
let json = xlsx.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
console.log(json)
};
};
3.导出excel
function exportExcel(result){
let sheet = xlsx.utils.json_to_sheet(result);
let keys = Object.keys(sheet).sort();
let ref = keys[1] + ':' + keys[keys.length-1];
let workbook = {
SheetNames:['nodejs-sheetname'],
Sheets:{'nodejs-sheetname':Object.assign({},sheet,{'!ref':ref})}//nodejs-sheetname 为sheet名字
}
xlsx.writeFile(workbook,filepath);
}
导入和导出excel多sheet道理是一样的,按照上面的即可!