前端导出word实现方法

如何实现?

npm i docxtemplater jszip-utils file-saver jszip@2.6.1
import Docxtemplater from docxtemplater
import JSZipUtils from jszip-utils
import { saveAs } from file-saver
import JSZip from jszip
wordData: any =  {
    title: "5月监控月报",
    data: [
      {
        name: "天气雷达",
        remark: "remark1",
        status: "70%"
      },
      {
        name: "探空雷达",
        remark: "remark2",
        status: "72%"
      }
    ]
}

放入word模板,在vue项目的public文件下面,且必须是.docx,不能是.doc

exportWord  () {
    let _this = this
    // 读取并获得模板文件的二进制内容
    JSZipUtils.getBinaryContent(report/word.docx, function (error:any, content:any) {
      if (error) throw error // 抛出异常
      let zip = new JSZip(content) // 创建一个JSZip实例,内容为模板的内容
      let doc = new Docxtemplater().loadZip(zip) // 创建并加载docxtemplater实例对象
      doc.setData({ ..._this.wordData }) // 设置模板变量的值
      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, 日报.doc)
    })
  }
经验分享 程序员 微信小程序 职场和发展