使用Angular 4

时间:2019-05-19 02:03:13

标签: json excel angular typescript

我有一个对象数组列表。我想将这些数据导出到Excel文件(.xlsx或.xls)。

还提供了Excel文件的模板。只需映射到现有的Excel文件即可。 Excel文件位于Angular项目本身中。如何使用Angular 4做到这一点。

[
   {
      "name": "Roshan",
      "age": "35"
   },
   {
      "name": "Ritika",
      "age": "29"
   }
]

以上数据应映射到列名分别为Employee_NameEmployee_age的Excel中。

1 个答案:

答案 0 :(得分:1)

尝试xlsx软件包

将xlsx安装到您的项目

 npm install xlsx --save

 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()
export class ExcelExportService {
    constructor() { }

    public exportAsExcelFile(json: any[], excelFileName: string): void {
        const worksheet: XLSX.WorkSheet = XLSX.utils.aoa_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);
    }

    private saveAsExcelFile(buffer: any, fileName: string): void {
        const data: Blob = new Blob([buffer], {
            type: EXCEL_TYPE
        });
        FileSaver.saveAs(data, fileName + EXCEL_EXTENSION);
    }
}

export class AppComponent {
  name = 'Angular 6';
  data: any = [{
    eid: 'e101',
    ename: 'ravi',
    esal: 1000
  },
  {
    eid: 'e102',
    ename: 'ram',
    esal: 2000
  },
  {
    eid: 'e103',
    ename: 'rajesh',
    esal: 3000
  }];
  constructor(private excelService:ExcelExportService ){

  }
  exportAsXLSX():void {
    this.excelService.exportAsExcelFile(this.data, 'sample');
  }
}