前段時間寫過一篇文章基于element實作背景管理系統,并提到excel表格導出功能,可能描述不是很詳細,現在單獨整理列出。
後端提供的接口:
// 下載下傳分揀清單
export function getAssormentExport(params) {
return request({
url: '/manage/health/assorment/export?ids=' + params,
responseType: 'arraybuffer', // 代表記憶體之中的一段二進制資料 必須加
method: 'get'
})
}
vue:點選按鈕調用接口
<el-button type="primary" size="mini" @click="addexport()">導出選中</el-button>
script:
// 導出選中
addexport() {
if (this.multipleSelection.length <= 0) {
this.$message({
showClose: true,
message: '未選中資料',
type: 'error'
})
return
}
for (let i = 0; i < this.multipleSelection.length; i++) {
this.ids.push(this.multipleSelection[i].id)
} // push一個新的數組,存儲需要導出資訊的ID并傳給接口實作資料傳回
getAssormentExport(this.ids).then(
function(response) {
const filename = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1]) || '分揀表.xlsx'
this.fileDownload(response.data, filename) // response.data是後端傳回的二進制資料流,filename是擷取到的導出檔案名,擷取失敗使用預設值
this.ids = []
}.bind(this)
).catch(
function(error) {
this.$message({
showClose: true,
message: error,
type: 'error'
})
this.ids = []
}.bind(this)
)
},
fileDownload(data, fileName) {
const blob = new Blob([data], {
type: 'application/octet-stream'
})
const filename = fileName || 'filename.xlsx'
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename)
} else {
var blobURL = window.URL.createObjectURL(blob)
var tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', filename)
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(blobURL)
}
},
檢視調用接口傳回的資訊

備注:
1.response傳回了包含響應頭所帶的所有資料,可以使用console.log(response)檢視列印資料,但是列印出來的資料隻能拿到預設的響應頭,這裡有個需要注意的地方。
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
如果想讓浏覽器能通路到其他響應頭的話,需要後端在伺服器上設定Access-Control-Expose-Headers
Access-Control-Expose-Headers : 'content-disposition'
後端大緻寫法:
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
這樣response.headers['content-disposition'].split(';')[1].split('=')[1] 就能取到接口傳回的檔案名稱了。
2. decodeURI的使用
decodeURI() 函數可對 encodeURI() 函數編碼過的 URI 進行解碼。
執行個體
在本例中,我們将使用 decodeURI() 對一個編碼後的 URI 進行解碼:
<script type="text/javascript">
var test1="http://www.w3school.com.cn/My first/"
document.write( encodeURI(test1) + "<br />")
document.write( decodeURI(test1) )
</script>
輸出:
http://www.w3school.com.cn/My%20first/
http://www.w3school.com.cn/My first/