How To Generate Excel File In Angular

How To Generate Excel File In Angular

In this article, we will learn how to read JSON data from API and export it into excel format in angular application, we will first read the data from the JSON API and then export the data into the excel format.

So Let’s with implementation,

First, we need to create a new angular project using the following command.

ng new exacel-export-example

Now, we need to install the file-saver and xlsx packages using the following command.

npm install file-saver --save
npm install xlsx --save

Now, we need to install the bootstrap using the following command and set the CSS style path.

npm install bootstrap

How To Generate Excel File In Angular

Now, we need to create a service file called excel-services.service.ts for the operation using the following command in the terminal.

ng g service ./services/excel-services

Now, add the following code under the excel-services.service.ts file.

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({
  providedIn: 'root'
})
export class ExcelServicesService {
  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);
  }
}

Now, add the following code under the app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { ExcelServicesService } from './services/excel-services.service';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'excel-upload-download';
  ngOnInit(){

  }
   excel=[];
    constructor(private excelService:ExcelServicesService,private http: HttpClient){
      this.getJSON().subscribe(data => {
        data.forEach(row => {
          this.excel.push(row);
        });
       });
    }
    
    exportAsXLSX():void {
       this.excelService.exportAsExcelFile(this.excel, 'sample');
    }
    public getJSON(): Observable<any> {
      return this.http.get('https://api.myjson.com/bins/zg8of');
    }
}

Now, add the following code under the app.component.html file.

<h3>Generate and Download Excel File in Angular 7</h3>
<div class="container">
<button (click)="exportAsXLSX()" class="btn btn-info mb-4 mt-2">Download Excel</button>
<table class="table table-striped table-bordered table-hover">
 <tr>
   <th>Name</th>
   <th>Month</th>
   <th>Sales</th>
   <th>Percentage</th>
 </tr>
 <tr *ngFor="let item of excel">
   <td>{{item.Name}}</td>
   <td>{{item.Month}}</td>
   <td>{{item.Sales_Figure}}</td>
   <td>{{item.Perc}}</td>
 </tr>
</table>
</div>

Now, using the following code adds the font awesome into the index.html file

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ExcelUploadDownload</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Now, run the application using the ng server command into the terminal and see the browser screen and click on the Download Excel button.

Conclusion

In this article, we learned how to read JSON data from API and export it into excel format in angular application.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post