递归实现大批量数据文件下载功能
elementui + vue 实现 大批量数据的excel文件下载。这里主要实现方式 通过点击按钮 导出表格功能。实现原理:类似于分页请求,为了在规定超时范围内将大批量数据导出。并且是同步实现,第一页的数据下载完成之后去下载第二页的数据。缺点:用户体验不佳,多文件导出。优点:在不超时的情况下 确保每条数据都能正常导出。
主要实现代码:
1.定义点击事件
handleClick(action,data){ if(action == 'import'){ // this.getDownload(); this.$loading({ lock: true, text: '正在下载中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }); this.getAllData(); } },
2.计算分页(this.total 为数据总条数,我这里定义了每次请求30万条数据。)
// 获取所有数据 getAllData(){ let downNumber = 300000; let totalNumber = Math.ceil(this.total / downNumber) for(let i=0;i<totalNumber;i++){ this.result.push(parseInt(i * downNumber + 1)); } this.upload(this.result) },
3.递归实现 数据请求
upload(alllocalId){ let res = [] let that = this; return new Promise((resolve,reject)=>{ let recursion = (alllocalId)=>{ that.$loading({ lock: true, text: '正在下载中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }); if(alllocalId.length){ let cur = alllocalId.pop() res.unshift(cur);//do it that.$axios({ url:'XXXX?applyId='+this.id+'&start='+ cur, methods:'get', responseType: 'blob', }).then(res=>{ download(res.data,'卡号卡密.xlsx') recursion(alllocalId) }) }else{ this.$loading().close(); resolve(res); } } recursion(alllocalId) })
4. download(res.data,'卡号卡密.xlsx') 为接收后台文件流转成excel 方法
export function download (data,titName) { if(!data){ return } const content = data const blob = new Blob([content],{type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}) const fileName = titName?titName: '自定义文件名.xls' if ('download' in document.createElement('a')) { // 非IE下载 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) // 释放URL 对象 document.body.removeChild(elink) } else { // IE10+下载 navigator.msSaveBlob(blob, fileName) navigator.msSaveBlob(blob) } }

浙公网安备 33010602011771号