Export to Excel on Angular 4

前端 未结 5 1859
春和景丽
春和景丽 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:57

    You can use XLSX for export to excel.

    It will support json or array into excel.

    Sample code

    import * as XLSX from 'xlsx';
    
    public exportAsExcelFile(json: any[], excelFileName: string): void {
      const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
      const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
      const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
      this.saveAsExcelFile(excelBuffer, excelFileName);
    }
    

    For Save

    private saveAsExcelFile(buffer: any, fileName: string): void {
      const data: Blob = new Blob([buffer], {
        type: EXCEL_TYPE
      });
      const today = new Date();
      const date = today.getFullYear() + '' + (today.getMonth() + 1) + '' + today.getDate() + '_';
      const time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
      const name = fileName + date + time;
      FileSaver.saveAs(data, name + EXCEL_EXTENSION);
    }
    

    Reference for Angular 2+

    Xlsx for angular 2+

提交回复
热议问题