vue中向docx模板填充数据并下载以及docx文件预览

发布时间 2023-06-01 08:19:49作者: wangyb56

一、向docx模板填充数据并下载

1.安装对应依赖

cnpm install docxtemplater pizzip --save-dev
cnpm install jszip-utils --save
cnpm install jszip --save
cnpm install file-saver --save

2.导入依赖包

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

3.定义函数封装方法

复制代码
/**
 4. 导出docx
 5. @param { String } tempDocxPath 模板文件路径
 6. @param { Object } data 文件中传入的数据
 7. @param { String } fileName 导出文件名称
*/
exportDocx(tempDocxPath, data, fileName){
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
    if (error) {
      throw error
    }
    const zip = new PizZip(content)
    const doc = new Docxtemplater().loadZip(zip)
    doc.setData(data)
    try {
      // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
      doc.render()
    } catch (error) {
      const e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      }
      console.log({
        error: e
      })
      // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
      throw error
    }
    const out = doc.getZip().generate({
      type: 'blob',
      mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    }) // Output the document using Data-URI
    //下载文件
    saveAs(out, fileName)
    // 这里如需预览,可使用window.URL.createObjectURL(this.out)将blob转为预览路径
  })
} 
复制代码

 

4.使用

4.1 首先将准备的模板文件放到static下

4.2 调用

this.exportDocx('/test.docx', {nickName:'小明同学'}, '测试.docx')

这里如果报下面这个错的话,一般是模板文件的路径错误导致。vue-cli版本如果是2,则应该有一个static的文件夹,将你的模板文件放入这个static文件夹中;如果是3,则有一个public文件夹,将模板文件放入这个public文件夹中。

 

 

二、docx文件预览

1.安装对应依赖插件

cnpm i docx-preview 

2.引入所需js,可下载放在public目录下

<script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>

3.使用