最近使用antd 做一個後臺管理系統中,業務場景下需要將數據導出為excel,後端使用POI,結果數據怎麼都無法生成,後面發現原來是前端限制了header 中可以接受的數據類型為json,無法接受blob的類型,後來改用了axios,就可以順利導出了,下麵是導出的代碼 ...
最近使用antd 做一個後臺管理系統中,業務場景下需要將數據導出為excel,後端使用POI,結果數據怎麼都無法生成,後面發現原來是前端限制了header 中可以接受的數據類型為json,無法接受blob的類型,後來改用了axios,就可以順利導出了,下麵是導出的代碼
1 import axios from 'axios'; 2 3 async function getExcel(url, fileName) { 4 const token = localStorage.getItem('token'); 5 axios 6 .get(url, { 7 responseType: 'blob', // 表明返回伺服器返回的數據類型, 8 headers: { 9 Authorization: 'Bearer ' + token, 10 Accept: 'application/json', 11 }, 12 }) 13 .then(res => { 14 const content = res; 15 const blob = new Blob([content.data], { 16 type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8', 17 }); 18 // return; 19 if ('download' in document.createElement('a')) { 20 // 非IE下載 21 const elink = document.createElement('a'); 22 elink.download = fileName; 23 elink.style.display = 'none'; 24 elink.target = '_blank'; 25 elink.href = URL.createObjectURL(blob); 26 document.body.appendChild(elink); 27 console.log(elink); 28 elink.click(); 29 URL.revokeObjectURL(elink.href); // 釋放URL 對象 30 document.body.removeChild(elink); 31 // window.location.reload(); 32 } else { 33 // IE10+下載 34 navigator.msSaveBlob(blob, fileName); 35 window.location.reload(); 36 } 37 }); 38 } 39 export default { 40 getExcel, 41 };