常常在項目開發(fā)中,我們會遇到下載表格到本地的功能,一般是前端發(fā)送請求,后端返回數(shù)據(jù)流的形式。
以下方法是通過純js實現(xiàn)的表格下載,親測有效哦。
html:
<el-button @click="exportExcel" type="primary" class="upload-demo">導出表格</el-button>
js:
// 下載表格文件
exportExcel () {
axios.get(url, {
headers:{
"Admin_token":token
},
responseType: 'blob', //二進制流
}).then(function (res) {
if(!res) return
const content = res
const blob = new Blob([content], {type: 'application/vnd.ms-excel'})
const fileName = '下載表格'+ '.xls'
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)
}
}).catch(function (error) {
console.log(error)
})
}
需要注意的地方是在發(fā)送請求的時候,需要設置responseType: 'blob'