导出两种方式:
1.和get请求一样,参数拼接在后面即可。
let url = `${process.env.VUE_APP_BASE_API}/statistics/dataExportDayOrMonth?dateType=${dateType}&startTime=${startTime}&endTime=${endTime}`;var $a = document.createElement('a');$a.setAttribute("href", url);$a.setAttribute("download", "");//兼容火狐//a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));var evObj = document.createEvent('MouseEvents');evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);$a.dispatchEvent(evObj);//导出功能兼容FireFox的代码var explorer = window.navigator.userAgent;if (explorer.indexOf("Firefox") >= 0) {//alert('Firefox');var downloadLink = document.createElement("a");downloadLink.href = url;//downloadLink.download = '统计.xls';document.body.appendChild(downloadLink);downloadLink.click();document.body.removeChild(downloadLink);}
2.post请求(和平时我们请求post接口一样,不过导出这里请求接口返回的是流,需要前端解析之后,然后通过a标签在浏览器中下载即可)。
export function exportDayOrMonthData(data) {return request({url: '/statistics/dataExportDayOrMonth',method: 'post',data:data,//服务器返回的数据类型(重点代码)responseType: 'blob',})}
exportDayOrMonthData(data).then(res=>{let blob = new Blob([res], {type:"application/force-download"}) // Blob 对象表示一个不可变、原始数据的类文件对象let fileReader = new FileReader() // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容fileReader.readAsDataURL(blob)//开始读取指定的Blob中的内容。一旦完成,result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容fileReader.onload = (e) => {let a = document.createElement('a')a.download = `日活统计.xlsx`a.href = e.target.result;document.body.appendChild(a)a.click()document.body.removeChild(a)}})
Blob对象表示一个不可变、原始数据的类文件对象。
FileReader 对象允许web应用程序异步读取存储在用户计算机上的文件内容。
