在vue中如何下载word模板并修改里面的数据

安装依赖

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

word模板样式

1、使用{字段名}方式定义好你想要获取的值

例如:请添加图片描述

2、将定义好的模板放在项目的public文件夹下

请添加图片描述

导入依赖包和函数封装

import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
/**
 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转为预览路径
  })
}

组件中使用

import { exportDocx } from "@/utils/exportWord";
exportDocx('/industry.docx', {year:2023,name:'xx'}, '文档.docx')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值