npm i xlsx
npm i file-saver
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { ExcelService } from './services/excel.service'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: [ExcelService] }) export class AppModule { } |
services/excel.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
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 ExcelService { 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' }); //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 + '_export_' + new Date().getTime() + EXCEL_EXTENSION); } } |
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import { Component } from '@angular/core'; import {ExcelService} from './services/excel.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) 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:ExcelService){ } exportAsXLSX():void { this.excelService.exportAsExcelFile(this.data, 'sample'); } } |
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<p> Exporting an excel file of type .xslx !!! </p> <p>Export as XLSX by clicking the below button</p> <button (click)="exportAsXLSX()"><i class="fa fa-file-excel-o" style="font-size:48px;color:blue"></i></button> <table> <tr> <td>Eid</td> <td>Ename</td> <td>Esal</td> </tr> <tr *ngFor="let item of data"> <td>{{item.eid}}</td> <td>{{item.ename}}</td> <td>{{item.esal}}</td> </tr> </table> |
app.component.css
1 2 3 4 5 6 |
p { font-family: Lato; } td { border: 1px solid black; } |
FULL SOURCE CODE