vue3 匯出為Excel檔案

小小小侠發表於2024-08-31

呼叫服務端介面匯出資料,瀏覽器調介面直接下載檔案,前端可以直接在window開啟

服務端介面其實是一個超連結了

<n-button type="primary" secondary  class="export" @click="exportOrder">匯出未開發票的訂單</n-button>
const exportOrder= async()=>{
let exportOrderOpenInvoiceUrl = `${import.meta.env.VITE_SERVER_URL}/order/exportOrderOpenInvoice`;
window.open(exportOrderOpenInvoiceUrl)
}

但如果需要token,最好還是在當前視窗開啟,跳另一個視窗token就沒了

匯出轉化為Excel
const exportOrder= async()=>{
 let reqData = {};
   let exportOrderOpenInvoiceUrl = "/order/exportOrderOpenInvoice"; 
   try {
     const response = await axios.get(exportOrderOpenInvoiceUrl, {
       params: reqData, 
       responseType: 'blob', 
    });
     if (response.data instanceof Blob) {
       const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
       const link = document.createElement('a');
       link.href = downloadUrl;
       link.setAttribute('download', '未開發票訂單.xlsx'); 
       document.body.appendChild(link);
       link.click();
       link.remove(); 
       window.URL.revokeObjectURL(downloadUrl); 
     }
   } catch (error) {
     console.error('匯出失敗:', error);
     message.error('匯出失敗');
   }
}

相關文章