流程:1.调用后端接口>>>>2.接口返回文件流>>>>>>3.下载文件
1.数据格式化
导出接口后端返回是文件流,所以接口需要加responseType: 'blob'
参数,另外使用transformResponse
对文件流数据格式化
exportUnitLog: {
url: '/unitlog/export',
responseType: "blob",
transformResponse(res) {
const returnRes = res
// 解析错误
if (returnRes.type === 'application/json') {
return {
success: true,
data: returnRes,
}
}
return {
success: true,
code: 0,
data: res,
message: '',
}
},
},
2.调用接口
async exportLog() {
const data = {
//参数
}
await service.exportUnitLog(data).then((res) => {
this.downloadCallback(res, '测点匹配失败日志.xlsx'); // 调用下载函数
})
},
3.下载
//生成下载文件
downloadCallback(res, fileName) {
const content = res
const blob = new Blob([content])
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)
}
},
上一篇
Vue2中简单使用TS
Vue2中简单使用TS
下一篇
input根据关键词过滤
input根据关键词过滤
版权声明:《 el-table导出excel 》为胡光喆原创文章,转载请注明出处!
最后编辑:2023-2-7 05:02:29