vue word模板下载 docxtemplater

一、安装插件

npm i docxtemplater

npm i pizzip

npm i jszip-utils

npm i file-saver

二、封装exportWord.js

import docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
// const TableModule = require("docxtemplater-table-module");
export function exportWord (form, table, docx, name) {
  if (!form && !table) return;
  //这里要引入处理图片的插件,下载docxtemplater后,引入的就在其中了
  // var ImageModule = require('docxtemplater-image-module-free')
  var self = this
  //这里是我的Word路径
  JSZipUtils.getBinaryContent(docx, function (error, content) {
    if (error) {
      throw error
    }
    let opts = {}
    opts.centered = true
    opts.fileType = 'docx'
    opts.getImage = (tag) => {
      return self.base64DataURLToArrayBuffer(tag)
    }
    opts.getSize = () => {
      return [550, 200] //输出的图片宽和高
    }
    let zip = new PizZip(content)
    let doc = new docxtemplater().loadZip(zip)
    doc.setData({//我的最外层包裹一切要导出的数据名称
      ...form,
      table,
    })
    try {
      doc.render()
    } catch (error) {
      var e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties,
      }
      throw error
    }
    var out = doc.getZip().generate({
      type: 'blob',
      mimeType:
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    })
    saveAs(out, name+".docx")
  })
}

三、引用

import { exportWord } from "@/utils/exportWord.js";

//导出word
function exportDoc(tableData) {
  let name = "天气预报";
  let docx = "/docx/export.docx";
  let from = {
     title: name,
  };
  exportWord(from, tableData, docx, name);
}

四、docx模板

五、效果展示

 

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值