模板文件 template.docx
工具
在给定了 word 模板的前提下,所要做的就是将数据填充到模板文件之中,docxtemplater
插件能够方便完成这个需求。
另外,还需要docx-preview
插件,将已经填充好数据的文件在页面上进行显示。
具体方法
在项目文件夹根目录下,创建static
文件夹,将template.docx 文件放入这个文件夹中
注意vue2.x
应该创建static
文件夹,vue3.x
应该创建的是public
文件夹
模板文档后缀注意是.docx
安装docxtemplater
,pizZip
,jSZipUtils
,docx-preview
, file-saver
cmd
复制代码
npm install docxtemplater --save
npm install pizZip --save
npm install jSZipUtils --save
npm install docx-preview --save
npm install file-saver --save
在文件中引入
js
复制代码
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { renderAsync } from 'docx-preview'
import {saveAs} from 'file-saver'
创建按模板导出方法
js
复制代码
exportWordDocx(tempDocxPath, dataObj, fileName, callback) {
// 读取并获得模板文件的二进制内容
JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
if (error) {
throw error
}
const zip = new PizZip(content)
const doc = new Docxtemplater().loadZip(zip)
//填充数据
doc.setData(dataObj)
try {
doc.render()
} catch (error) {
const e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
}
console.error({
error: e
})
throw error
}
const out = doc.getZip().generate({
type: 'blob',
mimeType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
//将生成文件的blob作为参数传入回调函数,为实现文件预览
//若不需要预览,可直接用下面这行代码
//saveAs(this.file, fileName);
callback(out);
})
}
调用按模板导出方法
js
复制代码
//要填充的数据
//通常请求后端接口获得
const dataObj = {
name: '探测器',
id: '002',
data: [
{position:'-15', average: '-15.3', difference: '-0.3'},
{position:'0', average: '0.2', difference: '0.2'},
{position:'15', average: '15.1', difference: '0.1'},
]
};
//文件名称
const fileName = `示例文件.docx`;
exportWordDocx(
`/static/template.docx`,
dataObj,
fileName,
(file)=>{
//预览功能
renderAsync(file, this.$refs.file);
//若要实现文档下载,可直接用下面这行代码
//saveAs(file, fileName);
//若要先预览,点击"下载"按钮之后再下载文档,
//可将file先暂存在this.file中,响应按钮事件后调用saveAs(this.file, fileName)
//this.file = file;
});
html
复制代码
<!-- 预览文档的放置容器 -->
<div ref="file"></div>
更改template.docx
这里的name
,id
,data
注意都是exportWordDocx
方法中dataObj
对象中的属性(例如步骤5代码中的dataObj
)
模板文档中的{参数名称}
原理是调用dataObj['参数名称']
来填充到文档中
若要实现数组的循环,可参照表格中的写法{#数组名称}...{数组元素对象属性名称}...{/数组名称}
。如上面文档中表格的写法,是取了dataObj
中属性名称为data
的数组,{position}
,{average}
,{difference}
都是数组元素对象的属性
预览效果与导出效果
之前碰到过这个问题:Uncaught Error: Error: Can't find end of central directory : is this a zip file ?
原因是模板文档路径没有找对,exportWordDocx
的第一个参数写成了/template.docx
,看其他人的说法,这样写会自动找static文件夹下面的文件的,不应该会出现这种问题。多番尝试解决不了的情况下直接改成/static/template.docx
就可正常获取了