const xlsx = require('node-xlsx');
express = require('express');
fs = require('fs');
router = express.Router(),
path = require("path")
//以上引入的工具都需要先在项目中安装
router.get('/export', (req, res, next) => {
//定义表格中的数据
let datas = [['表头1','表头2','表头2'],['表头1下对应的数据','表头2下对应的数据','表头3下对应的数据']]
});
//定义每列的宽度
const options = {'!cols': [{wch: 20}, {wch: 10}, {wch: 10}]};
var buffer = xlsx.build([{name:"Excel",data:datas}]);
let excelPath = path.resolve(__dirnam,'../../生成表格存储路径/存入的名字.xlsx'
fs.writeFile(excelPath ,(err) => {
if(!err){
//download 参数1 文件路径 参数2 文件名称 参数3 回调函数
res.download(excelPath ,'下载之后的名字.xlsx', (err){
if(!err){
//下载完成之后删除存在项目中的文件
fs.unlinkSync(excelPath )
}else{
consoel.log('下载失败')
}
})
}else{
console.log("生成文件失败!")
}
}))
前端页面通过window.location.href = '/export '调取下接口即可生成文件,通过前端页面还以传参给export接口,接口通过req.query拿到参数