
在做一些後台的報表數據時,可能會遇到,點擊【下載】按鈕後,直接實現下載 Excel 文件功能。

前端需要解析後端返回的二進制流文件,返回新建立的 Blob 物件,再創建 a 標籤,利用 a 標籤的 href 屬性,載入數據流,同時還可以自定義文件名稱。
API 設定 responseType
Axios api
在 API 的地方加上 responseType: 'blob'
1 2 3 4 5 6 7
| export function exportExcel() { return request({ url: '/excel/file', method: 'GET', responseType: 'blob', }); }
|
建立 Blob
var aBlob = new Blob( array, options );
自訂檔名
可以利用 download 屬性來自定義下載檔案名稱
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| async downloadExcel() { try { const res = await exportExcel(); const url = URL.createObjectURL(new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', })); const link = document.createElement('a'); link.href = url; link.download = '文件檔案名稱'; document.body.appendChild(link); link.click(); } catch (err) { console.log(err); } },
|
抓 content-disposition 取得檔名
抓取 header 的 content-disposition 填入檔案名稱
如瀏覽器支援 filename*=UTF-8
則顯示此檔名
如不支援則顯示 filename=
的檔名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| async downloadExcel() { try { const res = await exportExcel(); const blob = new Blob([res.data], { type: res.data.type }); const url = window.URL.createObjectURL(blob); const disposition = res.headers['content-disposition']; const filenameDecode = decodeURIComponent(disposition).split("filename*=UTF-8''")[1]; const filename = disposition.split('filename=')[1].split(';')[0]; const link = document.createElement('a'); link.href = url; if (filenameDecode) { link.download = filenameDecode; } else { link.download = filename; } document.body.appendChild(link); link.click(); } catch (err) { console.log(err); } },
|
REFERENCE
前端下载excel文件
MDN
🚀線上課程分享
線上課程可以加速學習的時間,省去了不少看文件的時間XD,以下是我推薦的一些課程
想學習更多關於前後端的線上課程,可以參考看看。
Hahow 有各式各樣類型的課程,而且是無限次數觀看,對學生或上班族而言,不用擔心被時間綁住
如果你是初學者,非常推薦六角學院哦!
剛開始轉職也是上了六角的課,非常的淺顯易懂,最重要的是,隨時還有線上的助教幫你解決問題!
Udemy 裡的課程非常的多,品質普遍不錯,且價格都滿實惠的,CP值很高!
也是很多工程師推薦的線上課程網站。