安装并导入
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
exportWord() {
const that = this
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent(
'previewDeclare.docx',
function (error, content) {
console.log(that.enterprise)
// gy-agree-service.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
// 抛出异常
if (error) {
throw error
}
console.log(content)
// 创建一个PizZip实例,内容为模板的内容
const zip = new PizZip(content)
// 创建并加载docxtemplater实例对象
const doc = new Docxtemplater().loadZip(zip)
doc.setOptions({
nullGetter: function () {
return ''
}
})
// 设置模板变量的值
doc.setData({
//trademark: that.trademark,
//planArr: that.planArr,
//JoinShop: that.JoinShop,
//recordList: that.recordList
})
try {
// 用模板变量的值替换所有模板变量
doc.render()
} catch (error) {
// 抛出异常
const e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
}
console.log(JSON.stringify({ error: e }))
throw error
}
// 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
const out = doc.getZip().generate({
type: 'blob',
mimeType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
// 将目标文件对象保存为目标类型的文件,并命名
saveAs(out, 'xxxxxx.docx')
}
)
},
首先,使用vue的时候,在public 文件夹下,放入word文档(先用word画好导出的样式)
如果是数组 注意开头的# 与结尾的/, #后面 /后面 是这个数组的名