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{
      
  }

});
相关推荐
啃火龙果的兔子11 小时前
前端导出大量数据到PDF方案
前端·pdf
咚咚咚小柒11 小时前
【前端】Webpack相关(长期更新)
前端·javascript·webpack·前端框架·node.js·vue·scss
诸葛韩信11 小时前
Webpack与Vite的常用配置及主要差异分析
前端·webpack·node.js
我只会写Bug啊1 天前
Vue文件预览终极方案:PNG/EXCEL/PDF/DOCX/OFD等10+格式一键渲染,开源即用!
前端·vue.js·pdf·excel·预览
showmethetime1 天前
使用 Node.js 和 Express 构建 RESTful API
node.js·restful·express
格兰芬多呼神护卫1 天前
python实现Latex格式的公式转OMML并写入word
python·c#·word
老友@1 天前
Docker 部署 Node.js + Playwright 项目,实现浏览器截图、打印和下载
docker·容器·node.js·playwright
帧栈2 天前
SpringBoot + iTextPDF + Acrobat 构建动态PDF表单的完整实践
spring boot·后端·pdf
前端摸鱼匠2 天前
Vue 3 事件修饰符全解析:从 .stop 到 .passive,彻底掌握前端交互的艺术
前端·vue.js·node.js·vue·交互