在vue中导出word

问题汇总:

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

参考文章

Vue-纯前端导出word文档_ChickenBro_的博客-CSDN博客_前端导出word

原因: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')

参考文章

vue报错:Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined_邵邵邵的博客-CSDN博客

vue过程中遇到的Uncaught (in promise) TypeError: Cannot read property ‘$message‘ of undefined - 程序员大本营

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

解决:

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

3、如果报下面这个错误,不用怀疑,就是word模板中的替换规则数据写错了,找到写错的地方改一下就行。

 

 

 docxtemplater文本替换规则

参考文档 

Types of tags | docxtemplater

1、简单的文本替换 

在模板中定义(input.docx): hello {name} !

设置数据(data.jsoon): {  name: “john" ; }

生成文件(output.docx): hello john !

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

在模板中定义:

{#hasKitty}Cat’s name: {kitty}{/hasKitty}

{#hasDog}Dog’s name: {dog}{/hasDog}

设置数据:

{
   "hasKitty": true,
    "kitty": "Minie",
    "hasDog": false,
     "dog": null
}

生成文件(output.docx):Cat’s name: Minie

{#repo} {name}  {/repo} {^repo}  No repos :(  {/repo} 

设置数据:

{
  "repo": []
}

生成文件(output.docx):No repos :(

设置数据: 

{
  "repo": [
      {name: "John"},
      {name: "Jane"},
  ]
}

生成文件(output.docx):John Jane

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

在模板中定义: 

   {#products}

     {name}, {price} €

  {/products}

设置数据:

{
    "products": [
        { name: "Windows", price: 100 },
        { name: "Mac OSX", price: 200 },
        { name: "Ubuntu", price: 0 }
    ]
}

生成文件(output.docx):

 Windows, 100 €

 Mac OSX, 200 €

 Ubuntu, 0€

 循环包含原始数据(例如字符串)的数组:

{
   "products": [
       "Windows",
       "Mac OSX",
       "Ubuntu"
   ]
}

在模板中定义: {#products} {.} {/products}

Windows Mac OSX Ubuntu

4、角度解析器  使用 angularParser 选项集,您还可以使用条件:

文档详细地址:Angular parser | docxtemplater

{#users.length>1}
There are multiple users
{/}

{#userName == "John"}
Hello John, welcome back
{/}

只有当有 2 个或更多用户时,第一个条件才会呈现该部分。

仅当 userName 是字符串“John”时,第二个条件才会呈现该部分。

它还处理以下运算符:

  • &&
  • 要么||
  • 添加+
  • 减法-
  • 三轮车a ? b : c
  • 带括号的运算符优先级(a && b) || c
  • 和其他一些 javascript 功能。

实现

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()
      });
    }

最终下载效果

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值