/* eslint-disable new-cap */
|
<template>
|
<div>
|
<el-button size="mini"
|
type="primary"
|
@click="exportclick(exportWordObj)"
|
icon="iconfont el-icon-daochu">
|
导出
|
</el-button>
|
</div>
|
</template>
|
|
<script>
|
import docxtemplater from 'docxtemplater'
|
import PizZip from 'pizzip'
|
import JSZipUtils from 'jszip-utils'
|
import { saveAs } from 'file-saver'
|
|
export default {
|
name: 'exportWord',
|
props: ['exportWordObj'],
|
data () {
|
return {
|
legendFlag: true
|
}
|
},
|
methods: {
|
exportclick (e) {
|
const docxsrc = '/word/moban.docx' // 模板文件的位置
|
const docxname = `抚州市${e.remark}洪水预警` // 导出文件的名字
|
|
e.region = e.real.addvnm
|
e.year = e.real.time.substr(0, 4)
|
e.month = e.real.time.substr(5, 2)
|
e.day = e.real.time.substr(8, 2)
|
e.hour = e.real.time.substr(11, 2)
|
e.Z = e.real.Z
|
e.yjsw = e.real.yjsw
|
e.fh = e.real.fh
|
|
// 读取并获得模板文件的二进制内容
|
JSZipUtils.getBinaryContent(docxsrc, function (error, content) {
|
// docxsrc是模板。我们在导出的时候,会根据此模板来导出对应的数据
|
// 抛出异常
|
if (error) {
|
throw error
|
}
|
|
// 创建一个PizZip实例,内容为模板的内容
|
const zip = new PizZip(content)
|
// 创建并加载docx templater实例对象
|
// eslint-disable-next-line new-cap
|
const doc = new docxtemplater().loadZip(zip)
|
// 设置模板变量的值
|
doc.setData({
|
...e // e中的数据可以再模板中直接使用
|
})
|
|
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'
|
mimeType: 'application/msword'
|
})
|
// 将目标文件对象保存为目标类型的文件,并命名
|
saveAs(out, docxname)
|
})
|
}
|
}
|
}
|
</script>
|
|
<style lang="scss" scope>
|
</style>
|