Vue-纯前端导出word文档

操作步骤:

1.安装

-- 安装 docxtemplater
cnpm install docxtemplater pizzip  --save

-- 安装 jszip-utils
cnpm install jszip-utils --save 

-- 安装 jszip
cnpm install jszip --save

-- 安装 FileSaver
cnpm install file-saver --save

2.在当前Vue文件中引入

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

3 创建模板文件 template.docx(完成word模板)

根据需要导出的word文件的要求,先使用word制作出模板,数据使用{变量} 代替。

注意:
模板文件推荐放在静态目录文件下。
使用vue-cli2的时候,放在static目录下。使用vue-cli3的时候,放在public目录下。
因为我在使用的时候,放入.vue文件的同级目录下,发现会读不到模板。

4.script代码

 // 点击导出word
  exportWord: function() {
    let that = this;
    // 读取并获得模板文件的二进制内容
    JSZipUtils.getBinaryContent("../../static/model.docx", function(error, content) {
      // model.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
      // 抛出异常
      if (error) {
        throw error;
      }

      // 创建一个PizZip实例,内容为模板的内容
      let zip = new PizZip(content);
      // 创建并加载docxtemplater实例对象
      let doc = new docxtemplater().loadZip(zip);
      // 设置模板变量的值
      doc.setData({
        table: that.videoParam.data  //接口返回数据(word需要填充的真是数据)
      });

      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 }));
        throw error;
      }

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

参考文章:

https://www.jianshu.com/p/b3622d6f8d98

https://www.jianshu.com/p/0de31429b12a

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值