1. 程式人生 > 其它 >vue前端匯出後端返回的word excel

vue前端匯出後端返回的word excel

在日常開發中,我們可能會遇到匯出excel word的情況,而後端此時給我們返回的是一個檔案流,需要前端將檔案流轉為url地址進行下載。 可以將這個方法封裝成一個工具類,方便其他地方呼叫,我這裡放到了utils.js裡面

js:

export function exportFile(data,type, fileName) {     let blob = new Blob([data], {       //type型別後端返回來的資料中會有,根據自己實際進行修改       // 表格下載為 application/xlsx,壓縮包為 application/zip等,         type: type     });     let filename = fileName;     if (typeof window.navigator.msSaveBlob !== "undefined") {       window.navigator.msSaveBlob(blob, filename);     } else {       var blobURL = window.URL.createObjectURL(blob);       // 建立隱藏<a>標籤進行下載       var tempLink = document.createElement("a");       tempLink.style.display = "none";       tempLink.href = blobURL;       tempLink.setAttribute("download", filename);       if (typeof tempLink.download === "undefined") {         tempLink.setAttribute("target", "_blank");       }       document.body.appendChild(tempLink);       tempLink.click();       document.body.removeChild(tempLink);       window.URL.revokeObjectURL(blobURL);     }   } 在vue中引用該方法         //匯出方法         exportFile() {             let obj = {                 dataid: this.companyInfo.dataId,                 id: this.companyInfo.id,                 template: this.radio,                 year: this.companyInfo.year             }             exportWordForQuality(obj)                 .then(res => {                     console.log('質量稽核-填報說明匯出:', res.data);                     const { data } = res                     let fileName = `${this.companyObj.companyName}執行報告稽核意見`                     exportFile(data, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', fileName)                 })                 .catch(err => {                     console.log(err);                 })
        }, 注意:
(1)本方法中並沒有設計壓縮,如倒出的檔案大,強烈建議使用jsZip 先安裝在使用:import JSZip from 'jszip' (2)exportWordForQuality ()介面中的響應格式要設定為bolb //下載質量稽核檔案 export function exportWordForQuality(data) {     return req.post('/qualityAudit/report/exportWordForQuality', data, {         'responseType': 'blob'     }) } (3)網頁響應頭content-type: word檔案: .doc格式的content-type設定為:application/vnd.msword;charset=utf-8  .docx格式的content-type設定為:application/vnd.openxmlformats-officedocument.wordprocessingml.document excel檔案: .xls格式的content-type設定為:application/vnd.ms-excel .xlsx格式的content-type設定為:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet   關於content-type設定格式參考:https://www.ibm.com/docs/en/wkc/cloud?topic=catalog-previews