Node.Js 实现模板生成Word、Word转Pdf文件、Excel生成、上传和下载

第三方插件依赖

复制代码
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{
      
  }

});
相关推荐
冴羽4 小时前
涨见识了,Error.cause 让 JavaScript 错误调试更轻松
前端·javascript·node.js
m***D2865 小时前
JavaScript在Node.js中的内存管理
开发语言·javascript·node.js
Hello eveybody5 小时前
Node.js环境变量配置实战
node.js
q***61505 小时前
Windows 上彻底卸载 Node.js
windows·node.js
q***4647 小时前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express
青靴8 小时前
轻量级 CI/CD:Git Hooks 自动部署 Node.js 应用(CICD-demo)
git·ci/cd·node.js
孟祥_成都8 小时前
别被营销号误导了!你以为真的 Bun 和 Deno 比 Node.js 快很多吗?
前端·node.js
诸神缄默不语9 小时前
如何用Python处理文件:Word导出PDF & 如何用Python从Word中提取数据:以处理简历为例
python·pdf·word
i***665010 小时前
SpringBoot实战(三十二)集成 ofdrw,实现 PDF 和 OFD 的转换、SM2 签署OFD
spring boot·后端·pdf
labixiong13 小时前
理解pnpm的本质,如何通过高效管理提升项目效率
前端·javascript·node.js