Export to Excel in Angular 6 | 7 | 8 | 9 | 10

How to export the data in excel in Angular

In Angular, we have different types libraries to export the data into excel file in different formats like (.xlsx, .xls, .csv). No need to communicate the server to export the data in excel file.

Here we need to know about two famous angular libraries to export the data in excel file. 

1. xlsx is a library to generate excel file in different formats with graphical design. Click here xslx ✋ to know more information about this library.

2. file-saver is a library to save the files in client side. Click here file-saver ✋ to know more information about this library. 

The main advantage of using this approach is, it will improve the performance to your application.

In this post, We can see how to implement the export to excel functionality using xlsx library in Angular.

Step 1 :  To create new application using angular cli, open Visual Studio code tool and open the terminal (ctrl + shift + ` ). 

CLI command for creating application : ng new ExportExcelSample

Step 2 : We are done creating the application with the name of 'ExportExcelExample'. Now need to install the 'xlsx' library.

CLI command for install xlsx library : npm i xlsx

Step 3 :  Once done the installation of xlsx library in your application. We need to install the file-saver library to save the files in client side. 

CLI command for install file-saver library : npm i file-saver

Step 4 : After installation of both libraries. We need to check whether it is installed or not. To check the version. Open package.json and check the version. 

Step 5 : We are done the setup. Now, we will implement the functionality to export the data in excel.

App.component.html

HTML
<p>Demo : Exporting an excel file of type .xslx !!! </p>
<p>Export as XLSX by clicking the below button</p>

<div style="width: 50%;">
  <button (click)="exportAsXLSX()" style="float: right;">Export to Excel</button>
  <br />
  <table style="width:100%;">
    <tr>
      <td>Id</td>
      <td>CarName</td>
      <td>Model</td>
      <td>Mileage</td>
      <td>Color</td>
    </tr>
    <tr *ngFor="let item of data">
      <td>{{item.Id}}</td>
      <td>{{item.CarName}}</td>
      <td>{{item.Model}}</td>
      <td>{{item.Mileage}}</td>
      <td>{{item.Color}}</td>
    </tr>
  </table>
</div>

App.component.scss

CSS
td {
    border: 1px solid black;
}

App.component.ts

Typescript
import { Component } from '@angular/core';
import { ExcelService } from '../app/excel.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'ExportExcelSample';

  constructor(private excelService: ExcelService) { }

  data: any = [{
    Id: 1,
    CarName: 'Hummer',
    Model: 'H3',
    Mileage: '196321',
    Color: 'Pink'
  }, {
    Id: 2,
    CarName: 'Chevrolet',
    Model: '1500 Silverado',
    Mileage: '195310',
    Color: 'Blue'
  }, {
    Id: 3,
    CarName: 'Infiniti',
    Model: 'M',
    Mileage: '194846',
    Color: 'Puce'
  }];

  public exportAsXLSX(): void {
    this.excelService.exportAsExcelFile(this.data, 'sample');
  }
}

Step 6 :  Create a service file with the name of  'ExcelService', then add the code.

CLI command for create excel-service file : ng g service excel-service


excel.serivce.ts

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

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

app.module.ts

Typescript
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { ExcelService } from './excel.service';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule
  ],
  providers: [ExcelService],
  bootstrap: [AppComponent]
})
export class AppModule { }

We are done the implementation, now we will run the project using cli command 'npm start' and will see the output.

Final Output looks like below.

Comments

Popular posts from this blog

Restrict Special Characters Using JavaScript By Copy,Paste

Create Custom Form Control for ng-select in Angular

Send API POST Request in MS SQL Server

Create Extension Method in typescript - String.IsNullOrEmpty()

Display PDF Or Tiff Files In IFrame

Create a function to convert from string to Decimal using JavaScript

Remove duplicate objects/data from an array of objects in Javascript