Angular使用插件導出表格Excel

如今前端均可以進行excel文件的簡單導入導出操做。
下面是使用插件導出表格成excel文件示例
組件是基於ng-alain封裝的 XlsxService,XlsService是基於sheetjs開發的。
文未附相關資源

示例代碼javascript

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" [ps]="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/前端

相關文章
相關標籤/搜索