基于docxtemplater的word模板处理vue组件
一、安装依赖npm install docxtemplaternpm install pizzipnpm install file-saver二、组件源码<template><el-button@click="renderDoc">文件下载</el-button></template><script>import Docxtemplate
·
一、安装依赖
npm install docxtemplater
npm install pizzip
npm install file-saver
二、组件源码
<template>
<el-button @click="renderDoc">文件下载</el-button>
</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 {
props: {
dataList: {
type: Object
}
},
methods: {
replaceErrors (key, value) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(function (error, key) {
error[key] = value[key]
return error
}, {})
}
return value
},
errorHandler (error) {
console.log(JSON.stringify({ error: error }, this.replaceErrors()))
if (error.properties && error.properties.errors instanceof Array) {
const errorMessages = error.properties.errors
.map(function (error) {
return error.properties.explanation
})
.join('\n')
console.log('errorMessages', errorMessages)
// errorMessages is a humanly readable message looking like this :
// 'The tag beginning with "foobar" is unopened'
}
throw error
},
renderDoc () {
// 解决异步参数传递问题
const _this = this
loadFile('https://docxtemplater.com/tag-example.docx', function (
error,
content
) {
if (error) {
throw error
}
var zip = new PizZip(content)
var doc = new Docxtemplater().loadZip(zip)
doc.setData(_this.dataList)
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render()
} catch (error) {
// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
this.errorHandler(error)
}
var out = doc.getZip().generate({
type: 'blob',
mimeType:
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
}) // Output the document using Data-URI
saveAs(out, 'output.docx')
})
}
}
}
</script>
三、组件调用
<template>
<div >
<Docxtemplater :dataList="this.data"/>
</div>
</template>
<script>
// @ is an alias to /src
import Docxtemplater from '@/components/docxtemplater.vue'
export default {
name: 'docxtemplater',
components: {
Docxtemplater
},
data () {
return {
data: {
first_name: 'John',
last_name: 'Doe',
phone: '0652455478',
description: 'New Website'
}
}
}
}
</script>
四、效果展示
【界面展示】
【word模板】
【数据生成】
五、示例下载
更多推荐
已为社区贡献1条内容
所有评论(0)