vue前端匯出後端返回的word excel
阿新 • • 發佈:2022-04-21
在日常開發中,我們可能會遇到匯出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); })}, 注意: