The project needs to realize exporting the table data to Excel through the export button.

The back end could have realized this function, but I did it by myself. Excel tables can be generated in the front end based on the table data obtained without any processing in the back end.

Background: ELment UI + VUE

Here are the detailed steps:

1. Download the dependency packages

npm install -S file-saver xlsx
Copy the code

or

npm install xlsx
npm install file-saver --save
Copy the code

2. Reference dependencies in the page

import FileSaver from "file-saver";
import XLSX from "xlsx";
Copy the code

3. Bind an ID selector to the table to export and an event to the query button

id="tableExcel"
Copy the code
@click="handleExport"
Copy the code

4. Write the bound event handleExport code

Notice that I’ve simply wrapped a function exportExcel to call the confirmation box. In addition, if you want to change the event name and selector name, you need to change the event name in template and JS simultaneously. The exported file name is query result.xlsx. You can also customize the change.

/** exportExcel () {let fix = document.querySelector(".el-table__fixed-right"); var xlsxParam = { raw: true }; If (fix) {// Determine whether there is fixed table in the node to be exported. If so, remove the DOM before converting excel. Wb = xlsx.utils.table_to_book (document.querySelector("#tableExcel").removechild (fix)); document.querySelector("#tableExcel").appendChild(fix); } else { // wb = XLSX.utils.table_to_book(document.querySelector('#tableExcel')); var wb = XLSX.utils.table_to_book( document.querySelector("#tableExcel"), xlsxParam ); } /* get binary string as output */ var wbout = XLSX.write(wb, { bookType: "xlsx", bookSST: true, type: "array", }); SaveAs (new Blob([wbout], {type: "application/octet-stream"}), "result.xlsx"); } catch (e) { if (typeof console ! == "undefined") { } } return wbout; }, handleExport () {this.$confirm(" Do you want to export all user data items?" , "confirmButtonText ", {confirmButtonText:" confirm ", cancelButtonText: "cancel ", type: "warning", }).then(() => { this.exportExcel() }).catch((rej) => { console.log(rej); })},Copy the code

Now that the code is complete, you can debug it to see if you can export the Excel you want.

Of course, there are other ways to do this, so please comment in the comments.