前端 下载excel文件

前端 下载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()

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值