主要邏輯
handleExportExcel(){
exportExcel().then(res=>{
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }) //
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', `花名冊列表-${dayjs().format('YYYY-MM-DD')}`)
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下載完成移除元素
window.URL.revokeObjectURL(url); // 釋放掉blob對象
})
}
注意點
-
首先前後端的響應類型應該相同
- 查看瀏覽器請求響應頭
content-type
值是否與Blob
構造函數中的type相同,各種MIME類型對應值查看 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
- 查看瀏覽器請求響應頭
-
注意亂碼問題
- 前端在請求接口中axios中設置
responseType:'blob'
resopnseType對應值查看http://www.axios-js.com/zh-cn/docs/#axios-create-config
export function exportExcel(data) { // 導出 return request({ url: '/exportExcel', method: 'post', responseType: 'blob', data }) }
- 前端在請求接口中axios中設置