1.npm安装依赖
npm install vue-json-excel
2.项目主文件入口main.js全局引入
import JsonExcel from 'vue-json-excel' Vue.component('downloadExcel', JsonExcel)
组件里面
import JsonExcel from 'vue-json-excel'
注册一下
components: {
downloadExcel: JsonExcel
},
在组件里面使用
<download-excel style="display:inline-block" :fields="jsonFields" :fetch="getTable" name="teacher_data_时间.xls" > <el-popover placement="bottom" width="160" v-model="visible" trigger="hover"> <p>选择导出列</p> <div style="text-align: right; margin: 0"> <div style="margin: 15px 0;"> <el-checkbox-group v-model="checkedJson" @change="handleCheckedCitiesChange" > <el-checkbox v-for="(item, index) in jsonList" :label="item.name" :key="index" style="float:left" >{{ item.name }}</el-checkbox > </el-checkbox-group> </div> </div> <el-button type="primary" slot="reference" :loading="ExcelFlag" >导出EXCEL</el-button > </el-popover> </download-excel>
上图解码
我们先看for="(item, index) in jsonList" v-model="checkedJson" @change="handleCheckedCitiesChange"
代码给你们贴上
mounted() { this.search() this.getArea() this.getVersionList() this.checkedJson = this.jsonList.map(item => item.name) this.getFields() }, methods: { // 复选框切导出列 handleCheckedCitiesChange(value) { this.getFields() }, // 整理fields数据格式 getFields() { this.jsonFields = {} this.checkedJson.forEach(item => { for (let i = 0; i < this.jsonList.length; i++) { if (this.jsonList[i].name === item) { this.jsonFields[this.jsonList[i].name] = this.jsonList[i].value } } }) },
我们再看:fetch="getTable" 这个回调函数写了什么
这个是searchAll()没啥讲解的就是获取数据 操作一下返回一下
async searchAll() { await this.search() this.ExcelList = [] this.ExcelFlag = true if (this.pages.total > 5000) { this.$message.warning('目前导出数量大于5000条,请缩小检索范围') } var body = { count: this.pages.total > 5000 ? 5000 : this.pages.total, liveid: this.form.liveId, teacherid: this.form.teacherId, teacherrole: this.form.teacherRole, area: this.form.area, version: this.form.version } return request({ method: 'get', url: ‘接口’, params: body }).then(res => { res.Content.Datas.forEach(item => { item.idName = `${item.TeacherID}(${item.TeacherName})` item.IPArea = `${item.IP}(${item.Area})` this.ExcelList.push(item) }) this.ExcelFlag = false return this.ExcelList })
上面开始调用了await this.search()
search() { this.loading = true var body = { page: this.pages.page, count: this.pages.count, liveid: this.form.liveId, teacherid: this.form.teacherId, teacherrole: this.form.teacherRole, area: this.form.area, version: this.form.version } return request({ method: 'get', url: '接口', params: body }).then(res => { this.loading = false this.realtimeList = res.Content.Datas this.pages = { total: res.Content.TotalNum, page: res.Content.PageNum, count: res.Content.PageSize } }) },
大家发现没有环环相扣的数据 最后是在searchAll这个函数返回的this.ExcelList才是我们想要的数据 要这个数据就先serach()获取数据
最后下下来的表格就是这样的 下载表格弹出文件夹
右侧赞助一下 代码改变世界一块二块也是爱