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

});
相关推荐
guslegend10 小时前
脚手架入门:必要性、核心功能与执行原理
前端·架构·node.js·脚手架·前端工程化
开开心心就好12 小时前
本地文件搜索工具推荐,占用小速度还快
智能手机·ffmpeg·ocr·word·音视频·网络攻击模型·安全架构
零基础12313 小时前
PDF 处理工具全攻略:pdf24、PDFgear、Adobe Acrobat DC 与 Stirling-PDF 深度对比
java·开发语言·pdf
xy345314 小时前
word技能--中文word文档通用格式标准化
word
南风微微吹14 小时前
考研数学一、二、三历年真题及答案解析PDF(1987-2026年)
考研·pdf
扶风ff14 小时前
练题簿在线免费刷题:题目导入、章节管理、Excel 与 Word 导出,让题库更好用
学习·小程序·word·excel
yivifu14 小时前
在Word中快速实现同类内容应用“双行合一”格式
word
开开心心就好17 小时前
视频压缩工具推荐,画质效果很能打
智能手机·ffmpeg·ocr·word·排序算法·音视频·散列表
HaipengYu1 天前
深度解密 OpenCode 2 插件加载机制:Dual-Version (V1/V2) 适配实战与官方文档的“隐形陷阱”
node.js
XLYcmy2 天前
PDF 论文处理器 — 改进方向与建议文档
python·pdf·llm·agent·dify·rag·harness