有时候业务需要做表格的导出功能的需求,以下是简单的方式:
我这里是封装了一下报表请求数据的api,注意:一定要写responseType:'blob',不然请求的数据会乱码,然后,点击报表时绑定了点击事件,
此时,我对事件做了个数据的大小判断,数据过于多提示放少些数据
1 exportReports() { // this.DefaultData.exportExcelMax限制一下导出的总条数 if (this.totals <= this.DefaultData.exportExcelMax) { this.$confirm('确定要导出当前' + this.totals + '条数据?', '提示', { dangerouslyUseHTMLString: true, confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => { this.getExpportData() }).catch(() => { }) } else { this.$confirm('当前要导出的' + this.totals + '条数据,数据量过大,不能一次导出! 2 建议分时间段导出所需数据。', '提示', { dangerouslyUseHTMLString: true, showCancelButton: false }).then(() => { }).catch(() => { }) } },
然后再调用了请求数据的接口,下面的时间上我是因为业务做了处理的,重要的代码就是
this.$http.exportExce请求里面的东西,可以直接复制使用
getExpportData(){ const loading = this.$loading({ lock: true, text: '正在导出,请稍等......', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }) const data = { "pageNum":this.currentPage, "pageSize":999999, "createdTimeFrom":this.startTime ? this.startTime + " " + "00:00:00" : getCurDate()+" " + "00:00:00" , "createdTimeTo": this.endTime ? this.endTime + " " + "23:59:59" : getCurDate()+" "+ "23:59:59" } this.$http.exportExcel('url',data).then(res=>{ console.log(res); const content = res.data const blob = new Blob([content]) console.log(blob); const fileName = getCurDate() + '-采购需求跟进报表'+'.xlsx'; /* `${new Date().getTime()}_导出结果.xlsx` */ if ('download' in document.createElement('a')) { const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) document.body.removeChild(elink) } else { navigator.msSaveBlob(blob, fileName) } loading.close() }).catch((r) => { console.error(r) message.error('导出失败') loading.close() }) },
注意:如果请求数据的传入分页的pageSize你可以传入无限大,这样就可以避免每次导出只能导出当前页的数据量