前端 下载excel文件
最简单的形式,
前端正常请求,后端返回一个静态文件链接,使用a标签的download方法
代码实现:
var a = document.getElementById('alink')
a.setAttribute('href', this.downloadUrl)
a.setAttribute('download', reportName)
a.click()
这种方式是比较耗资源的,后端需要把数据转化为excel存起来,返回一个文件地址
常用方式
后端返回一个blob格式的文件流,前端做操作,下载文件。
这里有一个坑,需要大家注意一下。
反正后台返回的都是一个文件流,那我的请求里就正常请求,不需要做操作了。
如此想法就大错特错了,前端的请求里还是要做操作的,不然会出现格式错误。
具体怎么操作,就是需要在请求里添加responseType: 'blob'
具体代码:
return axios({
method: 'post',
baseURL: global_.httpUrl,
url,
data: JSON.stringify(data),
timeout: 10000,
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': window.localStorage.getItem('token'),
'storeToken': window.localStorage.getItem('storeToken')
},
responseType: 'blob'
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
现在就可以对返回的blob二进制文件流做操作了。
var a = document.getElementById('alink')
var blob = new Blob([ret], {'type': 'application/vnd.ms-excel'})
this.downloadUrl = window.URL.createObjectURL(blob)
a.setAttribute('href', this.downloadUrl)
var reportName = 'report.xlsx'
a.setAttribute('download', reportName)
a.click()
ok?应该可以下载了。
如果运气好的话,确实可以下载了,但是
你前端下载的格式需要和后端返回格式相同,
例如都是xlsx或者csv和xls。
至此,就可以实现文件的下载了。
不过,可以进一步优化一下,一般的都会定义文件名
var a = document.getElementById('alink')
var blob = new Blob([ret], {'type': 'application/vnd.ms-excel'})
this.downloadUrl = window.URL.createObjectURL(blob)
a.setAttribute('href', this.downloadUrl)
var storeName = window.localStorage.getItem('userName')
var date = new Date()
var time = date.toLocaleDateString()
var reportName = global.AppName + '-' + storeName + time + '.xls'
a.setAttribute('download', reportName)
a.click()