公司项目需求:根据用户选择导出word报告,之前考虑使用积木报表,但是大概看了一下文档,发现并不适用于word报告的生成,后来问了一下朋友,他们是使用wps,觉得有点麻烦,于是继续搜索,发现了docxtemplater框架。
传送门:docxtemplater
技术栈: vue + ant-design-vue
安装依赖包,我使用npm,可根据自己喜好选择
npm i --save docxtemplater
npm i --save pizzip
npm i --save file-saver
使用过程:
<template>
<div>
<a-button @click="exportWord">click</a-button>
</div>
</template>
<script>
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import PizZipUtils from 'pizzip/utils/index.js'
import { saveAs } from 'file-saver'
function loadFile(url, callback) {
PizZipUtils.getBinaryContent(url, callback)
}
export default {
name: 'dom',
components: {},
props: {},
data() {
return {
//模板中所需要的数据
demoData: {
district: '地区',
day: 5,
section_name: '断面1',
data: [
{
create_date: '2021-10-10',
section_name: '断面1',
water_type: 'currency',
cod: 'cod2',
ad: 'ad2',
zl: '200',
cmon: '200',
},
],
},
}
},
computed: {},
watch: {},
created() {},
mounted() {},
methods: {
exportWord() {
let _this = this
loadFile('template6.docx', function (error, content) {
if (error) {
throw error
}
const zip = new PizZip(content)
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
})
doc.render(_this.demoData)
const out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
})
saveAs(out, 'output.docx')
})
},
},
}
</script>
<style scoped lang="less">
</style>
以上代码就可以实现纯文字的文档导出,比较简单,很多协调部分都需在模板中改动,目前正在尝试table表格的插入。。。