1.实现此功能需要使用到docxtemplater
、jszip-utils
、jszip
、FileSaver
等js文件
安装yarn add docxtemplater@^3.9.1
2. 创建word文档,字段以{#变量名}开始{/变量名}结束,对应字段对应变量名,{#List} {/List}表示循环List这个数组中的对象(注意:数组中的值必须为对象,且以key-value形式,才可以通过key值渲染对应value值)
{NAME}
统计时段:{startTime}至{endTime} 单位:元
乘车站名称
费
应付金额
{#tableone}{PassengerName}
{Centerlaborcosts}
{Amount due}{/tableone}
合计:
制表单位:{TabUnit} 制表人:{TabPeople} 领导签字: 打印时间:{Time}
3. docx模板存放位置:使用vue-cli2的时候,放在static目录下;使用vue-cli3的时候,放在public目录下
4.页面使用,引入及方法
import JSZipUtils from 'jszip-utils'
import JSZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import { saveAs } from 'file-saver'export default {
name: 'About',
data() {
return {
A1List: [],
A2List: [],
A3List: [],
B1List: [],
}
},
methods: {
exportWord() {
const _this = this
JSZipUtils.getBinaryContent('test.docx', function(error, content) {
// 抛出异常
if (error) {
throw error
}
// 创建一个JSZip实例,内容为模板的内容
let zip = new JSZip(content)
// 创建并加载docxtemplater实例对象
let doc = new Docxtemplater().loadZip(zip)
// 设置模板变量的值
doc.setData({
A1List: _this.A1List,
A2List: _this.A2List,
A3List: _this.A3List,
B1List: _this.B1List,
})
try {
// 用模板变量的值替换所有模板变量
doc.render()
} catch (error) {
// 抛出异常
this.$message.error('导出报表失败')
throw error
}// 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
let out = doc.getZip().generate({
type: 'blob',
mimeType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
})
// 将目标文件对象保存为目标类型的文件,并命名
saveAs(out, '费用.docx')
})
},
},
}
</script>