1.由于后端写导出功能比较耗费性能,因此采用前端导出excel。
2.安装依赖
npm install vue-json-excel
3.如果是很多地方使用,可以在main.js中引用。
如果是单个文件中使用,可以在该文件中引用。
import Vue from 'vue';
import JsonExcel from 'vue-json-excel'
Vue.component('downloadExcel', JsonExcel)
4.相关可配置信息
5.方法1:适用于无查询条件时的表格导出。
<template>
<div>
<download-excel
:data = "excelData"
:fields = "jsonFields"
type = "xls"
header = "问卷调查结果"
name = "xx问卷调查结果汇总.xls"
>
<button type="primary">导出</button>
</download-excel>
</div>
</template>
<script>
import JsonExcel from "vue-json-excel";
export default {
components: {
DownloadExcel: JsonExcel,
},
data() {
return {
jsonFields: {
年份: "year",
评价对象员工ID: "id",
评价对象: "objectId",
部门: "department",
性别:{
field: "sex",
callback: (value) => {
if (value === 'M') {
return "男";
} else {
return "女";
}
},
},
},
excelData: [],//导出表格数据
};
},
mounted() {
// 调取接口获取数据赋值给this.excelData
},
};
</script>
6.方法2:适用于有查询条件的表格导出。
<template>
<div>
<download-excel
:fetch = "fetchData"
:before-generate = "startDownload"
:before-finish = "finishDownload"
:fields = "jsonFields"
type = "xls"
header = "问卷调查结果"
name = "xx问卷调查结果汇总.xls"
>
<button type="primary" :loading="downLoading">导出</button>
</download-excel>
</div>
</template>
<script>
import JsonExcel from "vue-json-excel";
export default {
components: {
DownloadExcel: JsonExcel,
},
data() {
return {
downLoading:false,//查询
jsonFields: {
年份: "year",
评价对象员工ID: "id",
评价对象: "objectId",
部门: "department",
性别:{
field: "sex",
callback: (value) => {
if (value === 'M') {
return "男";
} else {
return "女";
}
},
},
},
};
},
methods() {
async fetchData(){
let obj = {
year: this.year,
name: this.name,
}
const response = await request.post(url, obj);
this.downLoading = false;
if(response.data.length === 0){
this.$message.info('暂无数据可导出!')
}
return response.data;
},
startDownload(){
this.downLoading = true;
},
finishDownload(){
this.$message.success('导出成功!')
}
},
};
</script>