Monday, August 12, 2019

How to Exporting an Excel file in Angular

Hello, this time I made a feature to deploy Excel export in Angular files in the web application we built with Angular 7. This is one of the features that are used frequently in our web application. There are different kinds of features that we try to achieve, a harmonious production .doc files as .doc, .docx, .xls, .xlsx, .csv, and several pdf files and some image files.

How to Exporting an Excel file in Angular 7

Today I'll show you how to Exporting an Excel file in Angular 7

Step 1. Enviroment Setup:

1. install Nodejs
2. Install Angular Cli 7
3. Update core Angular
4 . install file-saver npm module
5. xlcx npm module

Step 2. Create new application

ng new ExportExcel

Step 3. install Libary 

npm i file-saver
npm i file-saver

Step 4. Create service excel with name class ExcelService

ng g s excel/ExcelService
you can coppy 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({
  providedIn: 'root'
})
export class ExcelServiceService {
  constructor() { }
  public exportAsExcelFile(json: any[], excelFileName: string): void {
   
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log('worksheet',worksheet);
    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);
  }
}

Step 5. Create folder model in have class CountryInfo

export class CountryInfo {
    country: string;
    hydro: number;
    oil: number;
    gas: number;
    coal: number;
    nuclear: number;
}
Create a array CountryInfo below
let countriesInfo: CountryInfo[]  = [{
    country: "USA",
    hydro: 59.8,
    oil: 937.6,
    gas: 582,
    coal: 564.3,
    nuclear: 187.9
}, {
    country: "China",
    hydro: 74.2,
    oil: 308.6,
    gas: 35.1,
    coal: 956.9,
    nuclear: 11.3
}, {
    country: "Russia",
    hydro: 40,
    oil: 128.5,
    gas: 361.8,
    coal: 105,
    nuclear: 32.4
}, {
    country: "Japan",
    hydro: 22.6,
    oil: 241.5,
    gas: 64.9,
    coal: 120.8,
    nuclear: 64.8
}, {
    country: "India",
    hydro: 19,
    oil: 119.3,
    gas: 28.9,
    coal: 204.8,
    nuclear: 3.8
}, {
    country: "Germany",
    hydro: 6.1,
    oil: 123.6,
    gas: 77.3,
    coal: 85.7,
    nuclear: 37.8
}];
after create class service in file CountryInfo.ts

@Injectable()
export class Service {
    getCountriesInfo(): CountryInfo[] {
        return countriesInfo;
    }
}

Step 6. Add Example css of table in app.component.scss

table, th, td{
    border-top:1px solid #ccc;
    border-bottom:1px solid #ccc;
    border-right: 1px solid #ccc;
    text-align: center;
}
table{
    border-collapse:collapse;
    width:100%;
}
th, td{
    text-align:left;
    padding:10px;
    text-align: center;
   
}
.content{
    background: yellow;
    width: 60%;
    margin: auto;
}
h1{
    text-align: center;
}
.boild{
    font-weight: bold;
    text-align: center;
    color: blue;
}
.export{
    width: 100%;
    height: 100px;
}
.center{
    position: relative;
    float: left;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    cursor: pointer;
}

Step 7. Code in file app.component.html


<h1> Export file Excel in angular 7</h1>
<div class="content">
  <div class="export">
    <img class="center" src="assets/image/excel.png" (click) ="exportExcel()"/>
  </div>
  <div class="tableData">
    <table>
      <tr>
        <td class="boild">Country</td>
        <td class="boild">Hydro</td>
        <td class="boild">Oil</td>
        <td class="boild">Gas</td>
        <td class="boild">Coal</td>
        <td class="boild">Nuclear</td>
      </tr>
      <tbody>
        <tr  *ngFor ="let country of countriesInfo">
         <td>
           {{country.country}}
         </td>
         <td>
          {{country.hydro}}
        </td>
        <td>
          {{country.oil}}
        </td>
        <td>
          {{country.gas}}
        </td>
        <td>
          {{country.coal}}
        </td>
        <td>
          {{country.nuclear}}
        </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
The result is like the image below:



you can download project at github.

1 comment: