Export to Excel on Angular 4

前端 未结 5 1865
春和景丽
春和景丽 2021-02-13 05:55

I have a data table that is dynamically populated using Angular 4. I would like to export the table to excel. How can I achieve this in Angular 4. I\'m looking for .xls and not

5条回答
  •  花落未央
    2021-02-13 05:56

    before install libary

    npm i file-saver
    npm i xlsx
    

    Create service excel with name class ExcelService ng g s excel/ExcelService you can coppy below code

    import { Injectable } from '@angular/core';
    import * as FileSaver from 'file-saver';
    import * as XLSX from 'xlsx';
    const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
    const EXCEL_EXTENSION = '.xlsx';
    @Injectable({
      providedIn: 'root'
    })
    export class ExcelServiceService {
      constructor() { }
      public exportAsExcelFile(json: any[], excelFileName: string): void {
    
        const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
        console.log('worksheet',worksheet);
        const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
        const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        this.saveAsExcelFile(excelBuffer, excelFileName);
      }
      private saveAsExcelFile(buffer: any, fileName: string): void {
        const data: Blob = new Blob([buffer], {
          type: EXCEL_TYPE
        });
        FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
      }
    }
    

    Create folder model in have class CountryInfo

    export class CountryInfo {
        country: string;
        hydro: number;
        oil: number;
        gas: number;
        coal: number;
        nuclear: number;
    }
    

    you can clone example export a file excel in angular at github

提交回复
热议问题