在項目中可能會遇到甲方要求,表格中的數據要能夠導出成xlx文件,方便傳閱。
我使用的是el-table組件和axios
關鍵代碼是在el-table中加
<el-table-column type="selection" //type='selection'很關鍵 width="55"> </el-table-column>
<el-button type="success" :disabled="multiple" @click="handleExport">導出</el-button>
<el-table :data="tableData" style="width:100%;" @selection-change="handleSelectionChange" ref="table" > //el-table中要有下面兩行代碼 @selection-change="handleSelectionChange" ref="table"
需要在data中定義的屬性
selectionData: null, // 表格被選中的數據 // 非多個禁用 multiple: true, ids: [],
axios記得下載並引入,下面是關鍵js代碼
handleSelectionChange(data) { this.selectionData = data; this.ids = data.map((item) => item.id); this.multiple = !data.length; }, handleExport() { let ids = []; const arr = []; this.selectionData.map((item) => { arr.push(item.id); }); ids = arr.join(","); axios({ methods: "get", url: process.env.VUE_APP_BASE_API + "/ccapi/yjxx/exportSydYjxxList?ids=" + ids, responseType: "blob", }).then((res) => { let url = window.URL.createObjectURL(res.data); // var fileType = "application/vnd.ms-excel;charset=utf-8"; // var fileType1 = // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"; // let url = window.URL.createObjectURL(//因為傳了responseType:blob參數返回的數據已經是blob樣式的,所以不用new Blob轉化了 // new Blob([res.data], { // type: fileType, // }) // ); this.downloadFile(url, "隨便一個名字.xls"); }); }, downloadFile(data, fileName) { if (!data) { return; } // const url = window.URL.createObjectURL(new Blob([res.data])); // const blob=new Blob([data]) // const url= URL.createObjectURL(blob); const link = document.createElement("a"); link.href = data; link.setAttribute("download", fileName); document.body.append(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(data); this.ids = []; },