(记录)React纯前端生成word文档

643 阅读3分钟

前言

最近搞后台管理系统的时候,项目中老大提了一个需求,他要求我用纯前端实现一个word文档导出功能,并且附模板。而且要自己定义模板支持数据导出在模板内 把我吓的我差一点都哭了,前端小白来说真得会谢

准备工作

整个功能用到的相关技术还比较多,毕竟涉及到文件操作自然得装不少轮子,其中最重要的是docxtemplater是个付费版,docxtemplater-image-module-free这个是开源版本,他俩文档一样,但是少一个都不行。

安装依赖

//-- 安装 docxtemplater
npm install docxtemplater pizzip  --save
//-- 安装 jszip-utils
npm install jszip-utils --save 
//-- 安装 jszip
npm install jszip --save
//-- 安装 FileSaver
npm install file-saver --save
//安装 docxtemplater-image-module-free
npm install --save docxtemplater-image-module-free 

引入

import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'

逻辑代码

 const exportWord = () => {
    console.log("1111");
    // 设置模板变量的值,这个就是模板里所插入的内容数据,根据需要写成动态就好了。
    var currentDate = new Date();
    var wordData = {
      name:'张三',
      birth:'1999/12/03',
      Gender:'男',
      Date:'2015',
      workers:'0119960005',
      education:'研究生',
      employment:'Employ',
      face:'党员',
      gaogao:'高管类',
      Professional :'正高',
      sj:currentDate.getFullYear().toString()
   };
  

   // 读取并获得模板文件的二进制内容,是docxtemplater提供的固定写法
   JSZipUtils.getBinaryContent("../人员年度考核表.docx", function (error, content) {
     console.log('content', content);  
     // 创建一个PizZip实例,内容为模板的内容
     let zip = new PizZip(content);
     console.log(zip, 'zip');   
     // 创建并加载docxtemplater实例对象
     let doc = new docxtemplater()
      
       .loadZip(zip)
       .compile();
     doc.resolveData(wordData).then(function () {
       console.log('ready');
       doc.render();
       var out = doc.getZip().generate({
         type: "blob",
         mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
       });
       // 将目标文件对象保存为目标类型的文件,并命名(起一个自己需要的名字就好了)
       saveAs(out, "人员年度考核表.docx");
     })
   });

  };


<div className="App">
      <button type="info" onClick={exportWord} >导出word文档</button>
</div>

关于模板及数据格式

模板是使用的正常的编辑好的word文档,这边建议创建的时候使用直接创建已docx后缀的,创建其他的后缀在修改后缀会导致后面找不到文件

如上代码 我模拟的数据wordData 那么在我的模板里面使用的就是已{ 数据名称 }的形式 如下图

image.png 然后在导出的时候 他会已下载的形式下载下来 然后打开就是下面这种

image.png

注意点

  • 创建的文件必须是docx的 如果后面去更改过的 可能会导致找不到文件会报错
  • 建议是docx放到public目录下,其他文件夹也可以,不过一定一定一定要检查路径是否正确

关于报错

The filetype for this file could not be identified, is this file corrupted ?Error: Can't find end of central directory: is this a zip file?" 这2个都是路径的问题 建议检查一下

因为是创建的新的脚手架来测试验证的功能 是没问题的 后续加入到正式版本 有报错会同步记录在里面

代码地址: gitee.com/ma_jinkun/t…