Generate And Download Excel File In Angular 7

In here, we will learn how we can read data from JSON using API and download it in Excel format in Angular 7.

In this article, we will learn how we can read data from JSON using API and download it in Excel format in Angular 7. We will first read the data from the JSON API and then download the data in Excel format using Angular 7.
 
Prerequisites
  • Basic knowledge of Angular 7
  • NodeJS must be installed
  • Angular CLI must be installed
  • An editor like Visual Studio Code
Let’s get started.
 
Create a new project from the terminal.
 
 
Open the newly-created project in Visual Studio Code.
 
 
Install the packages required for the operation,
 
  1. npm install file-saver --save  
  2. npm install xlsx --save  
Create a service named excel-services.service.ts file for the operation using the terminal.
 
  1. ng g service ./services/excel-services  
Install the bootstrap and add it in the angular.json file.
  1. npm install bootstrap  
 
Now, we are all done with the installation and setup.
 
Open the excel-services.service.ts file and add the following code into it.
  1. import { Injectable } from '@angular/core';  
  2. import * as FileSaver from 'file-saver';  
  3. import * as XLSX from 'xlsx';  
  4. const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';  
  5. const EXCEL_EXTENSION = '.xlsx';  
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class ExcelServicesService {  
  10.   constructor() { }  
  11.   public exportAsExcelFile(json: any[], excelFileName: string): void {  
  12.     const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);  
  13.     const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };  
  14.     const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });  
  15.     this.saveAsExcelFile(excelBuffer, excelFileName);  
  16.   }  
  17.   private saveAsExcelFile(buffer: any, fileName: string): void {  
  18.      const data: Blob = new Blob([buffer], {type: EXCEL_TYPE});  
  19.      FileSaver.saveAs(data, fileName + '_export_' + new  Date().getTime() + EXCEL_EXTENSION);  
  20.   }  
  21. }  
Here is the code for app.component.ts.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { ExcelServicesService } from './services/excel-services.service';  
  3. import { HttpClient } from '@angular/common/http';  
  4. import { Observable } from 'rxjs';  
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent implements OnInit {  
  11.   title = 'excel-upload-download';  
  12.   ngOnInit(){  
  13.   }  
  14.    excel=[];  
  15.     constructor(private excelService:ExcelServicesService,private http: HttpClient){  
  16.       this.getJSON().subscribe(data => {  
  17.         data.forEach(row => {  
  18.           this.excel.push(row);  
  19.         });  
  20.        });  
  21.     }  
  22.       
  23.     exportAsXLSX():void {  
  24.        this.excelService.exportAsExcelFile(this.excel, 'sample');  
  25.     }  
  26.     public getJSON(): Observable<any> {  
  27.       return this.http.get('https://api.myjson.com/bins/zg8of');  
  28.     }  
  29. }  
Open the app.component.html file and add the below code into it.
  1. <h3>Generate and Download Excel File in Angular 7</h3>    
  2. <div class="container">    
  3. <button (click)="exportAsXLSX()" class="btn btn-info mb-4 mt-2">Download Excel</button>    
  4. <table class="table table-striped table-bordered table-hover">    
  5.  <tr>    
  6.    <th>Name</th>    
  7.    <th>Month</th>    
  8.    <th>Sales</th>    
  9.    <th>Percentage</th>    
  10.  </tr>    
  11.  <tr *ngFor="let item of excel">    
  12.    <td>{{item.Name}}</td>    
  13.    <td>{{item.Month}}</td>    
  14.    <td>{{item.Sales_Figure}}</td>    
  15.    <td>{{item.Perc}}</td>    
  16.  </tr>    
  17. </table>    
  18. </div>   
Here is the code for app.module.ts.
  1. import { BrowserModule } from '@angular/platform-browser';    
  2. import { NgModule } from '@angular/core';    
  3. import { HttpClientModule } from '@angular/common/http';    
  4. import { AppRoutingModule } from './app-routing.module';    
  5. import { AppComponent } from './app.component';    
  6. @NgModule({    
  7.   declarations: [    
  8.     AppComponent    
  9.   ],    
  10.   imports: [    
  11.     BrowserModule,    
  12.     AppRoutingModule,    
  13.     HttpClientModule    
  14.   ],    
  15.   providers: [],    
  16.   bootstrap: [AppComponent]    
  17. })    
  18. export class AppModule { }   
Open the index.html file present in the root folder and add the font awesome reference to it.
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>ExcelUploadDownload</title>    
  6.   <base href="/">    
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9.   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">    
  10. </head>    
  11. <body>    
  12.   <app-root></app-root>    
  13. </body>    
  14. </html>     
Output
 
 
Please give your valuable feedback/comments/questions about this article. Please let me know how you liked and understood this concept and how I could improve it.
 
You can download the source code from here.