vue3 导出为Excel文件

 

调用服务端接口导出数据,浏览器调接口直接下载文件,前端可以直接在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('导出失败');
   }
}
posted @ 2024-08-31 10:35  小小小侠  阅读(70)  评论(0编辑  收藏  举报