Saif Ali
Saif Ali

Reputation: 547

Converting Angular Data table to xlsx file

I have a data table in angular. I want the the data table to be downloaded as xlsx file when the user clicks the download button.

I tried with this article https://medium.com/@madhavmahesh/exporting-an-excel-file-in-angular-927756ac9857 But this is not working with Angular 7.

What is the best approach to achieve this ?

Upvotes: 1

Views: 5005

Answers (2)

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

You can do this with the help of Blob and file-saver:

TS code:

Install file-saver using

npm i angular-file-saver

and

import { saveAs } from 'file-saver';

ExportTOExcel()
{
   var blob = new Blob([document.getElementById("exportable").innerText], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
      });
   var fileName = 'your_name.xls';
   saveAs(blob, fileName);
}

for HTML add id="exportable" to the respective table.

Working StackBlitz

Upvotes: 2

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

Execute npm i xlsx

HTML:

 <div class="example-container mat-elevation-z8 " #TABLE>
      <table mat-table #table [dataSource]="dataSource">

        <!--- Note that these columns can be defined in any order.
              The actual rendered columns are set as a property on the row definition" -->

        <!-- Position Column -->
        <ng-container matColumnDef="position">
          <th mat-header-cell *matHeaderCellDef> No. </th>
          <td mat-cell *matCellDef="let element"> {{element.position}} </td>
          //..................................rest of the html
        <button mat-raised-button color="primary" (click)="exportAsExcel()">Export as Excel</button></div>

In your Component

import {Component,ViewChild, ElementRef} from '@angular/core';
 import * as XLSX from 'xlsx';
//......
    export class AppComponent  {
      @ViewChild('TABLE') table: ElementRef;
    exportAsExcel()
    {
      const ws: XLSX.WorkSheet=XLSX.utils.table_to_sheet(this.table.nativeElement);//converts a DOM TABLE element to a worksheet
      const wb: XLSX.WorkBook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      /* save to file */
      XLSX.writeFile(wb, 'SheetJS.xlsx');

    }
    }

Demo: https://stackblitz.com/edit/angular-uyanwz

Upvotes: 1

Related Questions