由于后端偷懒,前端就要累死累活的干,后端数据给我,我把数据弄成word导出,可恶!还好我会一点点。
no bb!show code!
安装依赖包
npm install docxtemplater
npm install pizzip
npm install file-saver
写成组件
<template>
<div>
<a-button @click="generate" type="primary" icon="download">{{exportBtnName}}</a-button>
</div>
</template>
<script>
import { getAction } from "@/api/manage.js"
import 'docxtemplater/build/docxtemplater.js'
import 'pizzip/dist/pizzip.js'
import 'pizzip/dist/pizzip-utils.js'
import 'file-saver'
export default {
data() {
return {
wordData: {
},
}
},
props: {
dataSource: {
type:Array,
default: () =>[]
},
getDataUrl:{
type:String,
default:''
},
time:{
type:String,
default:''
},
params:{
type:Object,
},
type:{
type:String,
},
templatePath: {
type:String,
},
exportBtnName: {
type:String,
default:'导出'
},
fileName:{
type:String,
default:'out.docx'
}
},
methods: {
// 导出word
loadFile(url, callback) {
PizZipUtils.getBinaryContent(url, callback);
},
generate() {
var that = this;
// this.loadFile('/serve'+that.templatePath, function (error, content) {
this.loadFile(that.templatePath, function (error, content) {
if (error) {
throw error
};
var zip = new PizZip(content);
var doc = new window.docxtemplater().loadZip(zip)
doc.setData({
...{dataSource:that.dataSource}
// 这里写要导出的数据
});
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, that.time.split('-')[0]+'年'+that.time.split('-')[1]+'月'+that.fileName)
})
},
}
}
</script>
<style scoped>
</style>
组件引入 注册使用即可
这里叫做 ExportBtn
<ExportBtn
templatePath="/summary.docx"
fileName="汇总表.doc"
exportBtnName="导出汇总表"
type="2"
style="margin-left: 8px"
:dataSource="dataSource"
:time="params.date"
></ExportBtn>
// dataSource:要导出的数据 传达组件里面
// fileName : 导出文件的名字,本来想写docx 但是由于领导可能还在用97 我就改成doc
// templatePath:要导出模板的地址
ok!说重点!
模板编写
要按照数据的格式来
比如:dataSource:[
{
realname:'芝芝龙',
right1:'√',
right2:'×',
right3:'',
right4:'',
right5:''
}
]
模板里面每个内容,由{}包着 如果是数组 用{#} {/}包着
会去替换模板文档里面的文字
模板路径,导出文件名,要导出的数据准备好,就可以导出了
这里写了一下我遇到的坑
1.not zip 文件
找到的模板文件路径对,但是内容有问题,解决方法:模板放在public文件夹下,路径直接写/xxx.doc
不要把模板放到assets下,找到的还是有问题
2.404 not found
其实也是一样的,都是路径问题,我放到服务器上发现直接去找域名加端口下的文件做模板(like this 0.0.0.0:8080/xx.doc)
这找的到才怪,所以我在上面有行注释的 可以看看 要打包发布了 加一下服务器上的模板路径
还好领导想了一下,不要有图片的,下次做一下有导出图片的
ad Time: qq群 903419026 (人工智能交流群) 群主和管理员都是大学玩人工智能的,后来一个去做后端一个去做前端,欢迎小伙伴一起入群探讨