首页 > 解决方案 > 使用 XLSX 导出 html 表时隐藏/删除列(表到表)

问题描述

我希望能够以 excel 文件格式导出我的 DOM 表。

我的功能(Typescript 3.5 / Angular 8)

ExportTOExcel() {
    const ws: XLSX.WorkSheet=XLSX.utils.table_to_sheet(document.getElementById('serversTable'));
    const wb: XLSX.WorkBook = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(wb, ws, 'Servers');

    /* save to file */
    XLSX.writeFile(wb, 'myproject.xls');
}

我的桌子:

<table id="serversTable" mat-table [dataSource]="serverArray" multiTemplateDataRows>
   <ng-container matColumnDef="number">
      <th mat-header-cell *matHeaderCellDef>Qty</th>
      <td mat-cell *matCellDef="let resourceGroup">
         ...
      </td>
   </ng-container>

   <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef>name</th>
      <td mat-cell *matCellDef="let  resourceGroup">
         ...
      </td>
   </ng-container>

   <!-- Other columns -->

   <ng-container matColumnDef="expandedDetail">
      ...
   </ng-container>

   <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
   <tr mat-row *matRowDef="let resourceGroup; columns: displayedColumns;" class="example- 
      element-row" [class.example-expanded-row]="expandedElement === resourceGroup 
      (click)="clickOnRowDisk(resourceGroup)">
   </tr>
   <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
</table>

expandedDetail是我不希望它出现在函数写入的文件中的列ExportTOExcel。此列是我的表格的最后一列。

我试过了

ws['!cols'] = [];
ws['!cols'][0] = { hidden: true };

但不起作用。

标签: angularangular-materialexport

解决方案


隐藏列

const ws: 
 XLSX.WorkSheet=XLSX.utils.table_to_sheet(document.getElementById('serversTable'));

ws['!cols'] = [];
ws['!cols'][12] = { hidden: true };
/* here 12 is your column number (n-1) */
const wb: XLSX.WorkBook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(wb, ws, 'Servers');
/* save to file */
XLSX.writeFile(wb, 'myproject.xls');

推荐阅读