一、安装依赖

npm install docxtemplater
npm install pizzip
npm install file-saver

二、组件源码
<template>
     <el-button  @click="renderDoc">文件下载</el-button>
</template>
<script>
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import PizZipUtils from 'pizzip/utils/index.js'
import { saveAs } from 'file-saver'

function loadFile (url, callback) {
  PizZipUtils.getBinaryContent(url, callback)
}
export default {
  props: {
    dataList: {
      type: Object
    }
  },
  methods: {
    replaceErrors (key, value) {
      if (value instanceof Error) {
        return Object.getOwnPropertyNames(value).reduce(function (error, key) {
          error[key] = value[key]
          return error
        }, {})
      }
      return value
    },
    errorHandler (error) {
      console.log(JSON.stringify({ error: error }, this.replaceErrors()))
      if (error.properties && error.properties.errors instanceof Array) {
        const errorMessages = error.properties.errors
          .map(function (error) {
            return error.properties.explanation
          })
          .join('\n')
        console.log('errorMessages', errorMessages)
        // errorMessages is a humanly readable message looking like this :
        // 'The tag beginning with "foobar" is unopened'
      }
      throw error
    },
    renderDoc () {
      // 解决异步参数传递问题
      const _this = this
      loadFile('https://docxtemplater.com/tag-example.docx', function (
        error,
        content
      ) {
        if (error) {
          throw error
        }
        var zip = new PizZip(content)
        var doc = new Docxtemplater().loadZip(zip)
        doc.setData(_this.dataList)
        try {
          // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
          doc.render()
        } catch (error) {
          // The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
          this.errorHandler(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>
三、组件调用
<template>
  <div >
    <Docxtemplater :dataList="this.data"/>
  </div>
</template>
<script>
// @ is an alias to /src
import Docxtemplater from '@/components/docxtemplater.vue'
export default {
  name: 'docxtemplater',
  components: {
    Docxtemplater
  },
  data () {
    return {
      data: {
        first_name: 'John',
        last_name: 'Doe',
        phone: '0652455478',
        description: 'New Website'
      }
    }
  }
}
</script>
四、效果展示

【界面展示】
在这里插入图片描述
【word模板】
在这里插入图片描述
【数据生成】
在这里插入图片描述

五、示例下载

https://download.csdn.net/download/qq_40981137/15364180

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐