el-table中的数据选择导出
在项目中可能会遇到甲方要求,表格中的数据要能够导出成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 = []; },