vue項目中導出Excel文件功能的前端代碼實現


在項目中遇到了兩種不同情況,

1、get請求導出文件,實現起來相對簡單

// 導出數據
exportData() {
window.location.href = `/oes-content-manage/role/export-roles?size=${this.totalCount}&sidx=roleName&sord=desc&roleId=${this.searchForm.roleId}`;
},

直接把要傳遞的參數拼接在請求地址url后面即可

2、post請求方式

// 查詢結果導出
exportResult() {
let key;
let param = {};
for (key in this.exportParam) {
if (key == 'page' || key == 'rows') {
continue;
} else {
param[key] = this.exportParam[key]
}
}
exportexcl(param).then(res => {
var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet這里表示xlsx類型
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); // 創建下載的鏈接
downloadElement.href = href;
downloadElement.download = '導出數據.xlsx'; // 下載后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 點擊下載
document.body.removeChild(downloadElement); // 下載完成移除元素
window.URL.revokeObjectURL(href); // 釋放掉blob對象
})
},

這種方式用於傳遞參數比較多的情況,在這個項目中所傳遞參數達到了三四十個。

同時不要忘記在接口加上responseType屬性。

// 查詢結果導出
export function exportexcl(params) {
  return axios.post(servers + '/program/export', params, {
    responseType: 'blob'
  });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM