-
requirement background
Our project will always encounter this kind of export table data function. For example, which table is checked, click Export, when exporting excel data, only the checked data will be exported, and when it is not checked, all data will be exported. We follow the normal logic. That is to say, it is necessary to adjust the interface of the backend. For example, when it is necessary to adjust the selected data, we may pass a parameter to the backend such as ids=[’11’,’22’], and pass it empty when exporting all. But through my encapsulated tool class, the front end of the data on the table can be exported by itself, and then let’s get to the point
-
Requires tool class encapsulation and implementation
-
In the vue project, use file-saver to export files, download Excel files, download pictures, download text, and those who are interested in file-saver can search for themselves, and we use the XLSX export form xlsx file plug-in in vue, our project Install npm first
npm install file-saver --save npm install --save xlsx
-
code show as below
import * as XLSX from "xlsx"; import { saveAs } from 'file-saver' /** * @Copyright export tool class * @Description: Export the array data returned by the interface to Excel * @param list * @param columns_list * @param tabData interface returned list data Array * @param sheetName the sheet name in excel to be exported String or Array * @param tableName the name of the excel to be exported String * @author Chensina * @date March 22, 2023 * @update [Number][Date YYYY-MM-DD][Name of person who changed][Description of change] */ export function exportAuto(list, columns_list, sheetName, tableName) { var reData = []; list. map((item, index) => { var reObj = {}; columns_list // .filter((item) => item.isShowCol) .forEach((value, key) => { if (value. label != undefined) { for (let i = 0; i < Object. keys(item). length; i ++ ) { if (value.prop == Object.keys(item)[i]) { if (value. prop == "num") { reObj[value.label] = index + 1; } else { reObj[value.label] = Object.values(item)[i]; } } } } }); reData.push(reObj); }); exportExcel(reData, sheetName, tableName); } /** * @Copyright export tool class * @Description: Export the array data returned by the interface to Excel * @param tabData interface returned list data Array * @param sheetName the sheet name in excel to be exported String or Array * @param tableName the name of the excel to be exported String * @author Chensina * @date March 22, 2023 * @update [Number][Date YYYY-MM-DD][Name of person who changed][Description of change] */ export function exportExcel(tabData, sheetName, tableName) { let isArrayData = Array.isArray(tabData), isArraySheet = Array.isArray(sheetName); /* create a new blank workbook */ let wb = XLSX.utils.book_new(); if (isArrayData & amp; & amp; isArraySheet) { tabData.forEach((item, index) => { XLSX.utils.book_append_sheet( wb, XLSX.utils.json_to_sheet(item), sheetName[index] ); }); } else { let sheet = XLSX.utils.json_to_sheet(tabData); let colWidths = []; let colNames = Object.keys(tabData[0]); // array of names of all columns // Calculate all cell widths for each column // loop through rows first tabData.forEach((row) => { // column number let index = 0; // loop through the columns for (const key in row) { if (colWidths[index] == null) colWidths[index] = []; switch (typeof row[key]) { case "string": case "number": case "boolean": colWidths[index].push(getCellWidth(row[key])); break; case "object": case "function": colWidths[index].push(0); break; } index + + ; } }); let wi = []; colWidths. forEach((widths, index) => { // Calculate the width of the column header widths.push(getCellWidth(colNames[index])); // set the maximum value as the column width //wi.push({ wpx: Math.max(...widths) * 5.5 }) wi.push({ wch: Math.max(...widths) }); }); sheet["!cols"] = wi; XLSX.utils.book_append_sheet(wb, sheet, sheetName); } let wbout = XLSX. write(wb, { bookType: "xlsx", bookSST: true, type: "array", }); try { //save document saveAs( new Blob([wbout], { type: "application/octet-stream;charset=utf-8", }), //`${tableName}_${new Date().Format('yyyy-MM-dd hh:mm:ss')}.xlsx` `${tableName}.xlsx` ); } catch (e) { if (typeof console !== "undefined") console. log(e, wbout); } } function getCellWidth(value) { // Determine whether it is null or undefined if (value == null) { return 10; } else if (/.*[\一-\龥] + .*$/.test(value)) { // Determine whether it contains Chinese return value.toString().length * 2.1; } else { return value.toString().length * 1.1; /* another solution value = value.toString() return value.replace(/[\Α-\¥]/g, 'aa').length */ } }
-
Requirement practice
-
page reference
<template> <div> <el-button type="primary" @click="exportExcel">Export</el-button> </div> </template>
//Define the fields to be exported according to your own needs. If some statuses are Y, N, you can process them yourself first if you want to export Chinese exportcolumns: [ { label: 'serial number', type: 'index' }, { label: 'Sales code', prop: 'setPrdCode', width: '180', sortable: true, }, { label: 'Sales item name', prop: 'setProductName', width: '180', sortable: true, }, { label: 'Sales item name 2', prop: 'setProductName2', width: '180', sortable: true, }, { label: 'Sales Part Status', prop: 'setProductStatusName', width: '180', }, { label: 'Marketing Organization', prop: 'salesOrgName', width: '180', }, { label: 'Product Line', prop: 'productLineName', width: '180', }, ],
import { exportAuto } from "@/utils/export.js"; // export exportExcel() { this.currentTime = this.getCurrentTime(); //Get the current time //Export selected data when data is selected on the page //this.multipleSelection table currently checked data //exportcolumns the fields you need to export if (this. multipleSelection & amp; & amp; this. multipleSelection. length > 0) { //Export checked data exportAuto( this.multipleSelection, //check the selected data this.exportcolumns, //Fields to be exported "Manufacturing code and sales code list", //sheet name in excel "Sales code and manufacturing code query results-" + this.currentTime //exported excel name ); } else { //export all if (!!this. list) { exportAuto( this.list, this. exportcolumns, "Manufacturing code and sales code list", "Sales code and manufacturing code query result-" + this.currentTime ); } } },
-
Screenshot of demand effect
-
When there is checked data
2. When there is no checked data and you directly click Export
The good friends are here to finish the demonstration. If you have any questions, please feel free to consult