Vue+elementUI 导出word打印

import JSZipUtils from "jszip-utils";
import JSZip from "pizzip";
import Docxtemplater from "docxtemplater";

npm安装以上依赖

首先维护个word模板

Vue+elementUI 导出word打印_第1张图片

导出方法

    //导出word
    skipOutWord(row) {
      var printData = row
      const data = JSON.parse(JSON.stringify(printData))
      data.timeYear = data.startTime.toString().split("-")[0]
      data.startTime = data.startTime.toString().split("-")[0]+'年'+data.startTime.toString().split("-")[1]+'月'
      data.endTime = data.endTime.toString().split("-")[0]+'年'+data.endTime.toString().split("-")[1]+'月'

      //set打印日期
      JSZipUtils.getBinaryContent('/template/projectApplication.docx', function (error, content) {
        // 抛出异常
        if (error) {
          throw error
        }
        // 创建一个JSZip实例,内容为模板的内容
        const zip = new JSZip(content)
        // 创建并加载docxtemplater实例对象
        const doc = new Docxtemplater().loadZip(zip)
        // 设置模板变量的值
        doc.setData({
          ...data,
        })
        try {
          // 用模板变量的值替换所有模板变量
          doc.render()
        } catch (error) {
          // 抛出异常
          // let e = {
          //   message: error.message,
          //   name: error.name,
          //   stack: error.stack,
          //   properties: error.properties,
          // }
          this.$message.error('导出失败')
          throw error
        }

        // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
        const out = doc.getZip().generate({
          type: 'blob',
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        })
        // 将目标文件对象保存为目标类型的文件,并命名
        saveAs(out, '汕头公司'+printData.startTime.toString().split('-')[0] + '年职工(青年)创新创效立项申报表.docx')
      })
    },

你可能感兴趣的:(VUE+elementUI,vue.js,elementui,前端)