关于VUE项目导出word文档

3,229 阅读1分钟

前段时间在公司做了个小项目,其中有个需求需要将页面导出为word文档,在这里记录一下用的方法以及步骤。

方法

模板导出法--其实就是先用word制造出一个模板,数据使用{变量}进行代替。类似于vue插槽。

具体步骤
  1. 安装一些js依赖和插件 npm install jszip-utils pizzip docxtemplater file-saver

  2. 创建word模板 类似于下图,其中

{#A1List} {/A1List}表示循环A1List这个数组中的对象(注意:数组中的值必须为对象,且以key-value形式,才可以通过key值渲染对应value值

{index},{optionName},{answer}表示对象中存放的key值

image.png

模板存放位置:使用vue-cli2的时候,放在static目录下;使用vue-cli3的时候,放在public目录下

image.png

  1. 组件中使用
import JSZipUtils from 'jszip-utils'
import JSZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import { saveAs } from 'file-saver'

export default {
  name: 'About',
  data() {
    return {
      A1List: [],
      A2List: [],
      A3List: [],
      B1List: [],
    }
  },
  methods: {
    exportWord() {
      const _this = this
      JSZipUtils.getBinaryContent('test.docx', function(error, content) {
        // 抛出异常
        if (error) {
          throw error
        }
        // 创建一个JSZip实例,内容为模板的内容
        let zip = new JSZip(content)
        // 创建并加载docxtemplater实例对象
        let doc = new Docxtemplater().loadZip(zip)
        // 设置模板变量的值
        doc.setData({
            A1List: _this.A1List,
            A2List: _this.A2List,
            A3List: _this.A3List,
            B1List: _this.B1List,
        })
        try {
          // 用模板变量的值替换所有模板变量
          doc.render()
        } catch (error) {
          // 抛出异常
          this.$message.error('导出报表失败')
          throw error
        }

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


  1. 效果展示

image.png