0
点赞
收藏
分享

微信扫一扫

在vue中导出word

郝春妮 2022-03-13 阅读 151

问题汇总:

1、 Uncaught Error: ReferenceError: JSZip is not defined  at XMLHttpRequest.xhr.onreadystatechange (index.js?0083:110:1)

原因:docxtemplater 不支持jszip,会有报错,因此要使用PizZip

解决:安装依赖npm install pizzip,使用PizZip

// let zip = new JSZip(content);
   let zip = new PizZip(content);

2、Uncaught TypeError: Cannot read properties of undefined (reading '$message')

原因: function(error, content){ }和(error,content)=>{ }中的this指向不同,箭头函数并不简单是匿名函数的简写

解决:

//function(error, content){ }
(error,content)=>{ }

 docxtemplater文本替换规则

1、简单的文本替换 

2、条件判断(条件以磅开头,以斜杠结尾。那是{#hasKitty}开始一个条件并{/hasKitty}结束它)

3、循环(在 docxtemplater 中,条件和循环使用相同的语法,称为 Sections)

实现

1、安装

npm install docxtemplater   --save
npm install jszip-utils --save 
npm install jszip --save
npm install file-saver --save
npm install pizzip --save

2、引入

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

 3、创建模板文件

4、实现代码

  exportWord() {
      let _this=this;
      const loading = this.$loading({
        lock: true,
        text: '正在生成word',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 读取并获得模板文件的二进制内容
      JSZipUtils.getBinaryContent("survey.docx", (error, content) => {
        // survey.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
        // 抛出异常
        if (error) {
          this.$message.error("导出word文档失败!")
          loading.close()
          throw error;

        }
        // 创建一个JSZip实例,内容为模板的内容
        // let zip = new JSZip(content); //用PizZip替代
        let zip = new PizZip(content);
        // 创建并加载docxtemplater实例对象
        // let doc = new window.docxtemplater().loadZip(zip);
        let doc = new docxtemplater().loadZip(zip);
        // 设置模板变量的值
        doc.setData({
          ..._this.form,
          expert: _this.expertList
        });

        try {
          // 用模板变量的值替换所有模板变量
          doc.render();
        } catch (error) {
          // 抛出异常
          let e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties
          };
          console.log(JSON.stringify({ error: e }));
          this.$message.error("导出word文档失败!")
          loading.close()
          throw error;
        }

        // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
        let out = doc.getZip().generate({
          type: "blob",
          mimeType:
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        });
        // 将目标文件对象保存为目标类型的文件,并命名
        saveAs(out, "现场调查通知书.docx");
        loading.close()
      });
    }

最终下载效果

举报

相关推荐

0 条评论