最近项目有个需求导出word,纯前端实现,查了查资料,用docxtemplater简直不要太简单。
直接把官网例子拿过来就可以了。!!!
官网地址
首先,新建一个docx文件,把模板先写好。
注意!!如果数据结构中存在数组。 用{#xxx}{/xxx} 包裹。
数据结构示例:
wordData: {
name: '导出word',
nameList: [{
name: "张三",
age: 16,
hobby: ['吃饭', '睡觉', '打豆豆']
},
{
name: "李四",
age: 19,
hobby: ['抽烟', '喝酒', '打麻将']
},
]
},
然后导入需要的包,
npm i docxtemplater pizzip file-saver --save
然后在需要的模块内引入
import 'docxtemplater/build/docxtemplater.js'
import 'pizzip/dist/pizzip.js'
import 'pizzip/dist/pizzip-utils.js'
import 'file-saver'
methods: {
// 导出word
loadFile(url, callback) {
PizZipUtils.getBinaryContent(url, callback);
},
generate() {
var that = this;
this.loadFile("../../static/word.docx", function (error, content) {
if (error) {
throw error
};
var zip = new PizZip(content);
var doc = new window.docxtemplater().loadZip(zip)
doc.setData({
...that.wordData
});
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render()
} catch (error) {
var e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
}
console.log(JSON.stringify({
error: e
}));
// The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
throw 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")
})
},
}
到此就完事了。
完整代码,安装完包之后直接运行就好。记得放入word模板!!!
<template>
<div>
<button @click="generate">导出</button>
</div>
</template>
<script>
import 'docxtemplater/build/docxtemplater.js'
import 'pizzip/dist/pizzip.js'
import 'pizzip/dist/pizzip-utils.js'
import 'file-saver'
export default {
data() {
return {
wordData: {
name: '导出word',
nameList: [{
name: "张三",
age: 16,
hobby: ['吃饭', '睡觉', '打豆豆']
},
{
name: "李四",
age: 19,
hobby: ['抽烟', '喝酒', '打麻将']
},
]
},
}
},
methods: {
// 导出word
loadFile(url, callback) {
PizZipUtils.getBinaryContent(url, callback);
},
generate() {
var that = this;
this.loadFile("../../static/word.docx", function (error, content) {
if (error) {
throw error
};
var zip = new PizZip(content);
var doc = new window.docxtemplater().loadZip(zip)
doc.setData({
...that.wordData
});
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render()
} catch (error) {
var e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
}
console.log(JSON.stringify({
error: e
}));
// The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
throw 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>
<style scoped>
</style>