根据后端返回文件流导出excel
思路:先封装方法导出方法---在项目封装好的axios请求中加入responseType: 'blob'---在页面中使用
步骤一
在utils中创建一个tool.js文件,并粘入以下代码
export function exportFile(data, type, fileName) {
const blob = new Blob([data], {
// type类型后端返回来的数据中会有,根据自己实际进行修改
// 表格下载为 application/xlsx,压缩包为 application/zip等,
type: type
})
const filename = fileName
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename)
} else {
var blobURL = window.URL.createObjectURL(blob)
// 创建隐藏<a>标签进行下载
var tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', filename)
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)// 移除dom元素
window.URL.revokeObjectURL(blobURL)// 释放bolb内存
}
}
步骤二
在封装好的axios中加入responseType: 'blob'

步骤三
先引入刚封装好的方法
import {exportFile} from '@/utils/tool.js'
页面使用 可以写一个button按钮绑定一个点击事件函数,然后调用请求
<el-button @click="getExcel"></el-button>
getExcel(){
const params = get请求的参数
getStadiumNeedUserExport(params).then(res => {
console.log(res);
const name = res.headers['content-disposition']//获取后台返回文件名
let b = name.lastIndexOf("=") //截取
let fileName = name.substring(b + 1, name.length);//下载后文件名
console.log(fileName);
const contentType =
'application/vnd.ms-excel'
exportFile(res.data, contentType, fileName)
})
}
注意:下载后的文件名要与后台返回文件名一致(主要后缀名要一致,否则下载后的文件打不开)
这里直接用后台返回数据名进行截取
步骤四
然后点击button就可以下载Excel啦~
可能的报错处理
1、被封装的请求拦截器拦截了

解决办法
判断文件类型,如果为后台返回的文件类型,则不进行拦截
if (res.headers['content-type'] === "application/x-xls") {
return res
}
2、下载文件类型与后台返回数据类型保持一致