在系统的统计功能里我们常常用到一些导出的功能,把我们查出的数据导出到excel中。大多数情况下我们可能会让后台把数据处理好传给前端一个流数据 或者是直接返回一个下载链接,但是这样会二次查询相同的数据如果数据量大的话可能会造成系统的压力。我们可以直接在第一次查询到数据后直接导出前端显示的数据这样就不会二次查询了。怎么做呢 下边一起来看一下
首先安装 vue-json-excel 插件
npm install vue-json-excel -S
然后在main.js中导入
import VueJsonExcel from 'vue-json-excel';
Vue.component('downloadExcel', VueJsonExcel);
然后在.vue文件中使用
先查询数据 查到数据给到提前声明好的变量exportExcelData,把exportExcelData绑定给download-excel组件的data,当点击导出时 会直接导出excel文件
<v-btn class="ml-4" color="#0078d4" @click="search(true)"
>查询</v-btn
>
<tip-view v-slot="{ on }" text="如需导出请先点击查询">
<!--data:导出的数据
fields:excelFields 表示excel表每一列的标题(title) 接口返回的json数据,若不指定每列的标题,默认导出全部字段
header:表格标题-->
<download-excel
class="export-excel-wrapper"
:data="exportExcelData"
name="统计报表.xls"
>
<v-btn
class="ml-4"
color="success"
v-on="on"
>导出</v-btn
>
</download-excel>
</tip-view
>
export default {
components: {
TableView,
FieldView,
TipView
},
data: () => ({
exportExcelData:null,
excelFields: {
机构:'organ',
人数:'total',
备注:'remark',
"身份证号":{
field:"sfz",
callback:value=>{
//防止数字过长导致变为科学计数法
return " "+value;
}
}
}
}),
methods: {
refreshTable() {
const ths = this;
ths.search();
},
search(isResetPage) {
const ths=this;
const setting = this.tableSettingObj;
setting.loading = true;
setting.desserts = [];
setting.total = 0;
http
.get("api/DataStatisticsReport/Statistics", {
params: fieldsDataObj
})
.then(res => {
setting.desserts = res.items;
setting.total = res.totalCount;
ths.exportExcelData=res.items;
this.init = true;
setting.loading = false;
}).catch(err=>{setting.loading = false;});
//console.log(fieldsDataObj);
}
}
}
效果