第三方插件依赖
const XLSX = require('xlsx');
const Docxtemplater = require("docxtemplater"); // 引入Docxtemplater模块
const Enumerable = require('linq');
const fs = require('fs');
const PizZip = require("jszip"); // 引入PizZip=>jszip模块
function genFile(templatePath,outPath,data){
if (!fs.existsSync(templatePath)) {
fs.mkdirSync(templatePath, { recursive: true });
// throw new Error("File not found");return;
}
var content = fs.readFileSync(templatePath, "binary");
// 解压文件的内容
const zip = new PizZip(content); // 创建一个新的PizZip实例
// 解析模板,并在模板无效时抛出错误,例如,如果模板是"{user"(没有闭合标签)
const doc = new Docxtemplater(zip, { // 创建Docxtemplater实例
paragraphLoop: true, // 允许段落循环
linebreaks: true, // 保持换行符
});
doc.render(data);
// 获取zip文档并将其生成为Node.js缓冲区
const buf = doc.getZip().generate({ // 生成文档的zip格式
type: "nodebuffer", // 生成类型为nodebuffer
compression: "DEFLATE", // 压缩类型为DEFLATE
});
fs.writeFileSync(outPath, buf); // 将渲染后的文档写入到downName.docx文件
}
模板文件参照

生成文件

excel文件如下
//移除不需要导出的列
for(var obj of newQualityData){
delete obj.deviceType;
delete obj.qualityType;
delete obj.sStation;
delete obj.taskType;
}
const ws = XLSX.utils.json_to_sheet(newQualityData);
var time=moment().format('x');//返回字符串型毫秒时间戳 (req.body.time).format("YYYYMMDDHHmmss")
// 创建一个新的工作簿并添加工作表
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
// 写入文件
// console.log(path.resolve(__dirname, '..'));//根目录
// console.log(path.resolve(__dirname, '../'));//上一级目录
var savePath=path.join(path.resolve(__dirname, '../')+"/download_file",`${time}.xlsx`);
XLSX.writeFile(wb, savePath);
res.send({code:200,res:true,str:`${time}.xlsx`});
上传和下载
//上传
router.all('/Common/Upload',async(req,res,next)=>{
try{
let ret_files=[];
if (req.files){
const allowedMimes = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'application/pdf',
'text/plain',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];// 允许的文件类型
let files;
files=req.files;
for(let file of files){
if (!allowedMimes.includes(file.mimetype)) {
res.send({code:500,rc:false,str:'不支持的文件格式!'});
}
let file_ext=file.originalname.substring(file.originalname.lastIndexOf('.')+1);//文件后缀
let file_name=moment().format('x')+"."+file_ext;//时间戳作为文件名称
fs.renameSync(process.cwd()+"/download_file/upload/temp/"+file.filename,process.cwd()+"/download_file/upload/"+file_name);//移动文件兵修改文件名称
ret_files.push({name:file_name,url:'/download_file/upload/'+file_name})
}
}
res.send({code:200,rc:true,ret_files});
}
catch(error){
console.log(error);
res.send({ code:500,rc: false,str: error.message});
}
finally{
}
});
//下载
router.all('/Common/Download',async(req,res,next)=>{
try{
res.download(process.cwd()+req.body.file_url);
}
catch(error){
console.log(error);
res.send({ code:500,rc: false,str: error.message});
}
finally{
}
});