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

});
相关推荐
用户847181054195 小时前
从0开始打造自己的个人智能体(一)——Deep Agents js环境配置与对话入门
node.js·agent
DS随心转小程序6 小时前
实测评测 AI 导出鸭转化效能,全方位优化 DeepSeek 输出 word 文档落地使用效率
人工智能·aigc·word·豆包·deepseek·ai导出鸭
减瓦12 小时前
从 0.1 到 26:一个运行时的十七年进化史
node.js
DevOpenClub12 小时前
用网页快照、静态 HTML 和 PDF 转换接口构建网页归档 Agent
前端·人工智能·pdf·html
AI导出鸭PC端13 小时前
AI 导出鸭一站式转换工具,ChatGPT 内容怎么生成 word 无需手动复制排版
人工智能·chatgpt·word·豆包·ai导出鸭
晓得迷路了13 小时前
栗子前端技术周刊第 140 期 - pnpm、Node 新 API 文档网站、Oxlint...
前端·javascript·node.js
孟陬1 天前
Node.js 测试报告格式一览和自定义 json 格式 `--test-reporter=spec | tap | dot | junit | lcov`
node.js
fthux1 天前
装闭 RenoPit 源码解析(13):生成AI装修闭坑PDF报告
人工智能·ai·pdf·开源·github
开开心心就好1 天前
批量图片OCR识别重命名工具完全免费
随机森林·智能手机·ocr·电脑·word·音视频·最小二乘法
星星在线2 天前
怎么使用Python生成PDF,我开源了PDF Report Generator
python·pdf·开源