Excel File Export In Angular Using Service

What is Angular?

 
Angular is a client side JavaScript Framework which allows us to create Reactive client-side applications.
 
It's a great approach for a Single Page Application.
 
By default it supports two-way data binding.
 

Why should we use Services in Angular?

 
Angular service methods can be invoked from any component of Angular, like Controllers, Directives, etc.
 
This helps in dividing the web application into small, different logical units which can be reused.
 
We use the @Injectable class decorators to automatically resolve and inject all the other classes. This only works if each parameter has a TypeScript type associated with it, which the DI framework uses as the token.
 

What is a dependency?

 
When module A in an application needs module B to run, then module B is a dependency of module A.
 
Dependency Injection is a way of architecting an application so code is easier to re-use, easier to test and easier to maintain.
 
Angular comes with a Dependency Injection (DI) framework of it’s own and it’s used throughout Angular code.
 

Implement Dependency Injection in Angular

 
Below are the ways to implement DI in Angular,
 
Using @Injectable() in the service
Using @NgModules() in the module
Using Providers in the component
 
Step 1
 
Create an Angular Project,
 
The command to create a new Angular project “ng new <myNewApp>”. Let's create an Angular project using the following commands. 
 
Excel File Export In Angular Using Service
 
Step 2 - Create a Service
 
Open the above created project in Visual Studio code and create service by using the following command “ng generate service <myService>”.
 
Excel File Export In Angular Using Service
 
Step 3
 
Create a JSON file from any location Ex [assets/yourfilename.json]. Store the array values once JSON is created.
Excel File Export In Angular Using Service
  1. {  
  2.     "Cardetails": [{  
  3.             "Id": 1,  
  4.             "CarName""Hummer",  
  5.             "Model""H3",  
  6.             "Mileage""196321",  
  7.             "Color""Pink"  
  8.         }, {  
  9.             "Id": 2,  
  10.             "CarName""Chevrolet",  
  11.             "Model""1500 Silverado",  
  12.             "Mileage""195310",  
  13.             "Color""Blue"  
  14.         }, {  
  15.             "Id": 3,  
  16.             "CarName""Infiniti",  
  17.             "Model""M",  
  18.             "Mileage""194846",  
  19.             "Color""Puce"  
  20.         },  
  21.     }  
Excel File Export In Angular Using Service
 
Step 4
 
Open the created service and add angular/http service by using the following command npm install @angular/http, using the follwing code.
  1. import {  
  2.     Http  
  3. } from '@angular/http';  
  4. export class {  
  5.     constructor(private http: Http) {}  
Step 5
 
Get the stored JSON file through the service that you have created.
  1. Getdata() {  
  2.     return this.http.get("assets/Cardetails.json").map(res => {  
  3.         return res.json()  
  4.     });  
  5.    }  
  6. }  
Excel File Export In Angular Using Service
 
Step 6
 
Add the below code in the file app.module.ts 
  1. import {  
  2.     HttpModule  
  3. } from '@angular/http'  
  4. import {  
  5.     XlsServiceService  
  6. }  
  7. rom './xls-service.service'  
  8. imports: [  
  9.         HttpModule  
  10.     ],  
  11.     providers: [  
  12.         XlsServiceService  
  13.     ],  
Step 7
 
Add the following code to the file “app.component.ts”
  1. import {  
  2.     XlsServiceService  
  3. } from './xls-service.service'  
  4. constructor(private excelservice: XlsServiceService) {}  
  5. ngOnInit() {  
  6.     this.Getdetails()  
  7. }  
  8. Getdetails() {  
  9.     this.excelservice.Getdata().subscribe(check => {  
  10.         this.listdetails = check.Cardetails  
  11.     });  
  12. }  
Step 8
 
Install file-saver and xlsx through the commands “npm install file-saver” and “npm install xlsx”
 
Now, open the ‘excel.service.ts' and paste the following code.
 
Step 9
 
Declare file type and file extesion with the below code.
  1. const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';          
  2. const EXCEL_EXTENSION = '.xlsx';  
Step 10
 
Code to export JSON in excel file.
  1. public exportAsExcelFile(json: any[], excelFileName: string): void {  
  2.     const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);  
  3.     console.log('worksheet', worksheet);  
  4.     const workbook: XLSX.WorkBook = {  
  5.         Sheets: {  
  6.             'data': worksheet  
  7.         },  
  8.         SheetNames: ['data']  
  9.     };  
  10.     const excelBuffer: any = XLSX.write(workbook, {  
  11.         bookType: 'xlsx',  
  12.         type: 'array'  
  13.     });  
  14.     this.saveAsExcelFile(excelBuffer, excelFileName);  
  15. }  
  16. private saveAsExcelFile(buffer: any, fileName: string): void {  
  17.     const data: Blob = new Blob([buffer], {  
  18.         type: EXCEL_TYPE  
  19.     });  
  20.     FileSaver.saveAs(data, fileName + '_export_' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds() + EXCEL_EXTENSION);  
  21. }  
Step 11
 
Open the file “app.component.html” and paste the following code to see the HTML template
  1. <button(click)="Exportelx()">GenreateXls</button>   
Step 12
 
In HTML page, add a button to call a click function to export an excel file which calls the method in service.
  1. Exportelx() {  
  2.     this.excelservice.exportAsExcelFile(this.listdetails, "Carinformation")  
  3. }  
To see the output in browser, use the following command “ng serve --open”
 
Excel File Export In Angular Using Service

Summary 

 
We learned how to export Excel files in Angular applications.


Similar Articles