Angular使用插件导出表格Excel

3次阅读

共计 1110 个字符,预计需要花费 3 分钟才能阅读完成。

当初前端都能够进行 excel 文件的简略导入导出操作。
上面是应用插件导出表格成 excel 文件示例
组件是基于 ng-alain 封装的 XlsxService,XlsService 是基于 sheetjs 开发的。
文未附相干资源

示例代码

import {Component} from '@angular/core';
import {STColumn, XlsxService} from '@delon/abc';

@Component({
  selector: 'components-xlsx-export',
  template: `
    <button nz-button (click)="download()">Export</button>
    <!-- 为了方便使用了 ng-alain 表格组件,也能够用 ng-zorro 或者其余库实现的表格。展示是主要的,重点是数据 -->
    <st [data]="users" ="3" [columns]="columns" class="mt-sm"></st>
    `,
})
export class ComponentsXlsxExportComponent {constructor(private xlsx: XlsxService) {}

  // 表格数据 - 模仿数据
  users: any[] = Array(100)
    .fill({})
    .map((_item: any, idx: number) => {
      return {
        id: idx + 1,
        name: `name ${idx + 1}`,
        age: Math.ceil(Math.random() * 10) + 20,
      };
    });
  columns: STColumn[] = [{ title: '编号', index: 'id', type: 'checkbox'},
    {title: '姓名', index: 'name'},
    {title: '年龄', index: 'age'},
  ];

  download() {
      // 组装要导出的数据
    const data = [this.columns.map(i => i.title)];
    this.users.forEach(i =>
      data.push(this.columns.map(c => i[c.index as string])),
    );
    // 应用组件 XlsxService 导出数据为 xls 文件
    this.xlsx.export({
      filename: '自定义命名列表.xlsx',
      sheets: [
        {
          data: data,
          name: 'sheet name',
        },
      ],
    });
  }
}

相干资源:
ng-alain XlsxService https://ng-alain.com/components/xlsx/zh
sheetjs https://sheetjs.com/

正文完
 0