解决上面的问题,请用如下代码:
<script>let exportExcel = function (apiUrl, postData, downloadFileName, headers, cb) {//apiUrl, postData, downloadFileName, headers, cb(传参说明:接口路径,接口传参,下载文件名,头部信息,回调函数)(typeof postData !== 'string') && (postData = JSON.stringify(postData));downloadFileName || (downloadFileName = '下载文件.xlsx');//如果.xlsx无法打开就改为.xls后缀名let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLDOM');xhr.open('POST', apiUrl, true);xhr.responseType = 'blob';// 这里的header内容根据具体业务来调整参数:xhr.setRequestHeader('cookie', '你的cookie');xhr.setRequestHeader('sessionId', '你的sessionId');// ----------------------------------------xhr.onreadystatechange = function () {if (xhr.readySsate === 4) {if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {cb && cb(true);//下载成功let blobData = xhr.response;let reader = new FileReader();reader.readAsDataURL(blobData), reader.onload = function (e) {let a = document.createElement('a');a.download = downloadFileName, a.href = blobData.size < 32767 ? e.target.result : URL.createObjectURL(blobData), a.style.display = 'none';document.body.appendChild(a), a.click();URL.revokeObjectURL(a.href), document.body.removeChild(a);};} else {cb && cb(false);//下载失败}} else {cb && cb(false);//下载失败}};};//调用方法:exportExcel(接口路径,接口传参,下载文件名,头部信息,回调函数)</script>