docxtemplater的基础使用

1,279 阅读1分钟

最近工作上遇到生成word的需求,使用过其他的html转word之类的库,最后发现docxtemplater这个库比较好用

import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
import Docxtemplater from 'docxtemplater'

自定义一个方法

/**有哪些文件名 */
type IDocName = 'report.docx' | 'repair.docx'

/**
 * @description 导出word文档
 * @param {*} templateDocx 模板文档名称
 * @param {*} data    文档数据
 * @param {*} fileName 生成的文件名
 */
export const useDocxtemplater = (templateDocx: IDocName, data: any = {}, fileName: string) => {
  // 读取并获得模板文件的二进制内容   (public文件夹下的 .docx文档)
  JSZipUtils.getBinaryContent(`/${templateDocx}`, async (error: any, content: any) => {
    // 抛出异常
    if (error) throw error

    // 创建一个PizZip实例,内容为模板的内容
    const zip = new PizZip(content)

    // 创建并加载docx templater实例对象
    const doc = new Docxtemplater().loadZip(zip)

    // 设置模板变量的值F
    doc.setData(data)
    // 空值设置为 ''
    doc.setOptions({
      nullGetter: () => ''
    })

    try {
      // 用模板变量的值替换所有模板变量
      doc.render()
    } catch (error: any) {
      console.log(`error ==>`, error)
    }

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

word模板文件

image.png

将模板word文件放到public文件夹下面, 测试一下

<script setup lang="ts">
const generateWord = () => useDocxtemplater('report.docx', { test1: '666', test2: 333 }, 'test')
</script>
<template>
  <div class="w-full h-full">
    <div>
      {{ lang('home.home') }}
    </div>
    <el-button @click="generateWord">生成word</el-button>
  </div>
</template>
<style lang="scss"></style>

image.png