Mat-table-exporter不兼容Angular16/17/18,求升级兼容方案
解决Angular 18中mat-table-exporter不兼容的XLS导出方案
方案1:结合@angular/cdk与xlsx库手动实现
mat-table-exporter底层依赖Angular CDK的表格能力,升级到Angular18后可以直接基于数据源配合xlsx库实现导出,无需依赖第三方导出库:
- 安装必要依赖:
npm install xlsx @angular/cdk
- 组件中编写导出逻辑:
import { Component, ViewChild } from '@angular/core'; import { MatTable } from '@angular/material/table'; import * as XLSX from 'xlsx'; @Component({ selector: 'app-your-table', templateUrl: './your-table.component.html' }) export class YourTableComponent { @ViewChild(MatTable) table!: MatTable<any>; displayedColumns: string[] = ['id', 'name', 'email']; dataSource = [...你的表格数据源]; exportToExcel() { // 将数据源转为Excel工作表 const worksheet = XLSX.utils.json_to_sheet(this.dataSource); // 创建工作簿并添加工作表 const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, '表格数据'); // 导出文件 XLSX.writeFile(workbook, '导出数据.xlsx'); } }
- 模板添加导出按钮:
<button mat-raised-button color="primary" (click)="exportToExcel()">导出为XLS</button> <mat-table [dataSource]="dataSource"> <!-- 你的列定义 --> <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef> ID </mat-header-cell> <mat-cell *matCellDef="let element"> {{element.id}} </mat-cell> </ng-container> <!-- 其他列配置... --> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>
方案2:使用兼容Angular 18的替代库
选择维护活跃、支持Angular18的第三方导出库,比如ngx-mat-table-exporter:
- 安装依赖:
npm install ngx-mat-table-exporter xlsx
- 模块中导入库:
import { NgxMatTableExporterModule } from 'ngx-mat-table-exporter'; @NgModule({ imports: [ // ...其他模块 NgxMatTableExporterModule ] }) export class YourModule { }
- 模板中直接使用导出指令:
<mat-table [dataSource]="dataSource" ngxMatTableExporter #exporter="ngxMatTableExporter"> <!-- 列定义 --> </mat-table> <button mat-raised-button (click)="exporter.exportTable('xlsx', {fileName: '表格数据'})">导出XLS</button>
方案3:自定义复杂场景导出逻辑
如果表格包含自定义渲染内容、合并单元格等复杂场景,可以先处理数据再导出:
exportToExcel() { // 手动处理数据,转换渲染文本或格式 const processedData = this.dataSource.map(item => ({ ID: item.id, 姓名: item.name, 邮箱: item.email, 状态: item.isActive ? '已激活' : '未激活' })); const worksheet = XLSX.utils.json_to_sheet(processedData); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, '处理后数据'); // 可选:调整列宽 worksheet['!cols'] = [ {wch: 10}, {wch: 15}, {wch: 25}, {wch: 12} ]; XLSX.writeFile(workbook, '自定义导出数据.xlsx'); }
注意事项
- 确保
xlsx使用最新稳定版,避免版本兼容问题 - 独立组件模式下,需在组件
imports数组中导入相关模块 - 复杂场景下,手动处理数据能更精准控制导出结果
内容的提问来源于stack exchange,提问作者Ganesh
相关产品推荐
相关产品推荐

