[Angular] Export excel from table or json

How to implement?

1.NPM packages installation

npm i xlsx
npm i file-saver
npm i @types/file-saver

2.Create a service called ExportExcel (export-excel.service.ts)

import { Injectable } from '@angular/core';

import * as fileSaver from 'file-saver';
import * as XLSX from 'xlsx';

@Injectable({
  providedIn: 'root'
})
export class ExportExcel {
  byJson(jsonData: any, fileName: string, header?: string[]): void {
    // create a worksheet
    const ws = XLSX.utils.json_to_sheet(jsonData, { header: header });
    // create a workbook
    let wb = XLSX.utils.book_new();
    // workbook append worksheet
    XLSX.utils.book_append_sheet(wb, ws, fileName);

    const data = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    fileSaver.saveAs(new Blob([data], { type: 'application/octet-stream' }), `${fileName}.xlsx`);
  }

  byTable(table: any, fileName: string): void {
    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(table);
    const workbook: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, ws, fileName);
    const excelBuffer: any = XLSX.write(workbook, {
      bookType: 'xlsx',
      type: 'array'
    });
    const data: Blob = new Blob([excelBuffer], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
    });
    fileSaver.saveAs(data, `${fileName}.xlsx`);
  }
}

3. There are two solutions to implement it.

a. Solution 1: export Excel by Table

// Solution 1: export Excel by Table
  @ViewChild('basicTable', { read: ElementRef }) nzTable!: ElementRef;

  exportExcelByTable(): void {
    const fileName = 'exportExcelByTable';
    this.expExcel.byTable(this.nzTable.nativeElement, fileName);
    console.log(this.nzTable.nativeElement);
  }

b. Solution 2: export Excel by Json

// Solution 2: export Excel by Json
  excelHeader = [
    {
      title: '#',
      fieldName: 'key'
    },
    {
      title: '姓名',
      fieldName: 'name'
    },
    {
      title: '年齡',
      fieldName: 'age'
    },
    {
      title: '地址',
      fieldName: 'address'
    }
  ];

  exportExcelByJson(): void {
    const fileName = 'exportExcelByJson';

    let jsonData: any;
    // listOfData from API
    jsonData = this.listOfData.map((row: any) => {
      let data: any = {};
      this.excelHeader.map((item: { fieldName: string; title: string }) => {
        data[item.title] = row[item.fieldName];
      });
      return data;
    });
    this.expExcel.byJson(jsonData, fileName);
  }

4. The full source code

import { NgFor } from '@angular/common';
import { ChangeDetectionStrategy, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzTableModule } from 'ng-zorro-antd/table';
import { ExportExcel } from 'src/custom/services/export-excel.service';

interface Person {
  key: string;
  name: string;
  age: number;
  address: string;
}

@Component({
  selector: 'app-pages-sample-export-excel',
  template: `
    
      
        
          Name
          Age
          Address
          Action
        
      
      
        
          {{ data.name }}
          {{ data.age }}
          {{ data.address }}
          
            Action 一 {{ data.name }}
            
            Delete
          
        
      
    
    
    
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [NzTableModule, NzDividerModule, NzButtonModule, NgFor, NzInputModule, FormsModule]
})
export class ExportExcelComponent implements OnInit {
  listOfData: Person[] = [
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park'
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park'
    },
    {
      key: '3',
      name: 'Joe Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park'
    }
  ];

  constructor(private expExcel: ExportExcel) {}

  ngOnInit(): void {}

  // Solution 1: export Excel by Table
  @ViewChild('basicTable', { read: ElementRef }) nzTable!: ElementRef;

  exportExcelByTable(): void {
    const fileName = 'exportExcelByTable';
    this.expExcel.byTable(this.nzTable.nativeElement, fileName);
    console.log(this.nzTable.nativeElement);
  }

  // Solution 2: export Excel by Json
  excelHeader = [
    {
      title: '#',
      fieldName: 'key'
    },
    {
      title: '姓名',
      fieldName: 'name'
    },
    {
      title: '年齡',
      fieldName: 'age'
    },
    {
      title: '地址',
      fieldName: 'address'
    }
  ];

  exportExcelByJson(): void {
    const fileName = 'exportExcelByJson';

    let jsonData: any;
    // listOfData from API
    jsonData = this.listOfData.map((row: any) => {
      let data: any = {};
      this.excelHeader.map((item: { fieldName: string; title: string }) => {
        data[item.title] = row[item.fieldName];
      });
      return data;
    });
    this.expExcel.byJson(jsonData, fileName);
  }
}

5. Test result

[Angular] Export excel from table or json_第1张图片

[Angular] Export excel from table or json_第2张图片

你可能感兴趣的:(UI,json,前端,angular,经验分享,excel,typescript)