画画的baby~

今天又是划水的一天~不过遇到一个新的功能开发,记录一下
功能需求: 需要根据点击的单位数据,下载一个记录该单位数据的登记证word文档的下载功能~

  1. 安装docxtemplater等需要的包

npm i docxtemplater pizzip file-saver --save

  1. 创建需要的模板docx文档; 使用vue2.0是可以放在static目录下,使用vue3.0时可放在public目录下(注意: 模板文档最好存放在此位置,不然可能会报路径错误等问题)
    注意: 模板中如果需要使用到遍历时,使用 {#数组名称}{/数组名称} 包裹即可

  2. 在需要的模块中引入使用

<template>
  <div>
    <button @click="generate">导出</button>
  </div>
</template>

<script>
  import 'docxtemplater/build/docxtemplater.js'
  import 'pizzip/dist/pizzip.js'
  import 'pizzip/dist/pizzip-utils.js'
  import 'file-saver'

  export default {
   
    data() {
   
      return {
   
        wordData: {
   
          name: '导出word',
          nameList: [{
   
              name: "张三",
              age: 16,
              hobby: ['吃饭', '睡觉', '打豆豆']
            },
            {
   
              name: "李四",
              age: 19,
              hobby: ['抽烟', '喝酒', '打麻将']
            },
          ]


        },
      }
    },

    methods: {
   
      // 导出word
      loadFile(url, callback) {
   
        PizZipUtils.getBinaryContent(url, callback);
      },
      generate() {
   
        var that = this;
        this.loadFile("/word.docx", function (error, content) {
     //url模板存放的位置
          if (error) {
   
            throw error
          };
          var zip = new PizZip(content);
          var doc = new window.docxtemplater().loadZip(zip)
          doc.setData({
   
            ...that.wordData    //导入到模板文档的数据对象
          });
          try {
   
            // render the document (replace all occurences of {
   first_name} by John, {
   last_name} by Doe, ...)
            doc.render()
          } catch (error) {
   
            var e = {
   
              message: error.message,
              name: error.name,
              stack: error.stack,
              properties: error.properties,
            }
            console.log(JSON.stringify({
   
              error: e
            }));
            // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
            throw error;
          }
          var out = doc.getZip().generate({
   
            type: "blob",
            mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          }) //Output the document using Data-URI
          saveAs(out, "output.docx")
        })
      },

    }
  }

</script>

<style scoped>

</style>

好啦,这样就完成了啦啦啦~

可能出现的问题报错:

出现此问题是因为模板url写的不对,找不到模板文档~
这里需要将文档存放在static(Vue2.0)或者public(Vue3.0)下,然后使用模板文档的url写成 “/模板文件名.docx” 即可

参考博客: https://blog.csdn.net/weixin_43753330/article/details/103461870