Exporting an Excel file in Angular
By: Madhava Kumar Ippili
Tags: Angular6, Export, Data, Excel, Angular Cli

Hi all, this time I came up with a feature to implement the exporting an Excel file in our web apps built with Angular. This is one of the frequently used feature in our web apps. There are different exporting features that we try to achieve like, exporting a

doc files like .doc, .docx,

spreasheats like .xls, .xlsx, .csv

pdf files and also some image files.

Today I will show you the way to export a xlsx file from angular6.

Environment setup:

Node version 8. Angular CLI 6. Angular core updated to Angular 6. file-saver npm module, xlsx npm module.

File-saver module will help to export a file.

xlsx module will help to create a .xlsx file with required data and filename.So combining these 2, after giving the data as input to xlsx module it will convert the given array data to excel view and assigns the name that we passed to it.

Here the xlsx module will make prepare the required workbook, sheet and sets the data in a tabular manner with in the cells.

Getting on the track:

Prepare a new angular project with Angular CLI with the below command:

ng new angular-file-exporter-demo

2. Once the project gets created and the npm install is successfull.Run the below commands:

npm install file-saver — save

npm install xlsx — save

3. Now move to the app directory and create a directory called services / sharedServices. Its up to you to use any one, I will go with services.

With in this directory generate a service file with the below command:

ng g service excel

And copy paste the 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()

export class ExcelService {

constructor() { }

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: '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);

}

}

4. Now move to the app.component.ts file and add the below code:

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 {

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');

}

}

Now we are done with creating a service and accessing it in out component, lets do the necessary changes in app.component.html to show the json data in a table and the export button.

5. Open the app.component.html and save the below code:

<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>

6. And also as a final step to show a icon on the export button, add the cdn path of font-awesome in the index.html file.

https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css

7. Now run the command ng serve and you go to localhost:4200 in the browser and you can see the below screen:

8. Just click on the excel file icon available above the table and you see an excel file getting downloaded.

Here you can find the working demo

Please drop comments with your suggestions.

Happy coding!!!