这段时间在开发后台管理系统,管理员要看自定义数据报表,所以要求能够把数据以excel表格形式导出,刚开始我是直接用get方式下载的,后来后台同事说要改post下载,改就改吧,下面说说这两种下载方式,提供给大家参考:
1.get 下载:
var downURL = '下载接口'
var getData = '?starTime=20180922&endTime=20180925'
var request = downURL+getData
window.open(request)
2.post下载
第一步:让后端将下载的接口的response header设置:
Content-disposition: attachment; filename=数据报表.xlsx(表示会直接下载文件,文件名为‘数据报表’)
Content-Type:application/octet-stream (二进制流数据,如常见的文件下载)
第二步:修改axios请求的responseType为blob,以post请求为例:
axios({
method: 'post',
url: '接口地址',
data: {
startTime: '20180922',
endTime:'20180925'
},
responseType: 'blob'
}).then(response => {
this.download(response)
}).catch((error) => {
})
第三步:请求成功,拿到response后,调用download函数
methods: {
download (data) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
}
}