1.安装node-xlsx
npm install node-xlsx
2.引入模块
var xlsx = require('node-xlsx'); var fs = require('fs');
3.代码
router.get('/export.html',function(req,res){ billModel.find().exec(function(err,data){ var datas=[]; var title = ['客户名称','项目名称','设备名称']//这是第一行 俗称列名 datas.push(title); data.forEach((element) => { var arrInner = []; arrInner.push(element.companyName); arrInner.push(element.companyName); arrInner.push(element.projectName); arrInner.push(element.ccc); datas.push(arrInner);//data中添加的要是数组,可以将对象的值分解添加进数组,例如:['1','name','上海'] }); var name='应付账款明细'+GetDateStr()+'.xlsx'; writeExcel(name,datas); res.download('./public/bill/'+name); }); }); function writeExcel(name,data){ var buffer=xlsx.build([{name:'sheet1',data:data}]); fs.writeFileSync('./public/bill/'+name+'.xlsx',buffer,{'flag':'w'}); } function GetDateStr(){ return new Date().toLocaleDateString(); }