Check the table header, and the front-end custom selects the exported columns as an excel table

The front end exports the table form to an excel form

insert image description here
First install the xlsx dependency, and then introduce import * as XLSX from 'xlsx' into the project;
after checking the table columns, you need to process the exported data.

 exportExcel() {
    
    
 //是否已勾选
    if (this.selectIndexs.length) {
    
    

      // tslint:disable-next-line: prefer-for-of 
      // this.body: 表格body 
      // this.head: 表格head
      for (let j = 0; j < this.body.length; j++) {
    
    
        const excelRow: object = {
    
    };
        this.selectIndexs.forEach(s => {
    
    
        // this.head : { value: label, checked: false }[] = [];
        // 注意:如果表头是一样的字符的话,导出的excel会合并到一列
          const name = this.head[s]['value'];
          // 如果值为空,用0填充
          excelRow[name] = isNil(this.body[j][s]) || this.body[j][s] === '' ? 0 : this.body[j][s];
        });
        this.excelTable.push(excelRow);
      }

    } else {
    
    
      this.message.error('请先选择表格字段!');
      return;
    }
    this.jsonToSheet(this.excelTable, 'excel.xls');
    this.excelTable = [];

  }

  jsonToSheet(json: any[], filename: string): void {
    
    
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    const workbook: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, filename);
  }

Guess you like

Origin blog.csdn.net/huangyinzhang/article/details/124117199