Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export Angular Material Table to excel or pdf or csv

i am creating an angular table using this example from angular material https://material.angular.io/components/table/overview is there anyway to export it in excel or pdf?

like image 654
Kamran Mushtaq Avatar asked Mar 08 '18 10:03

Kamran Mushtaq


2 Answers

In your table component.ts

declare a value called renderedData: any;

Then in your constructor subscribe to the data that has been changed in your material table. I am guessing you are using a filterable table.

constructor(){
this.dataSource = new MatTableDataSource(TableData);
this.dataSource.connect().subscribe(d => this.renderedData = d);
}

npm install --save angular5-csv

In your HTML create a button <button class="btn btn-primary" (click)="exportCsv()">Export to CSV</button>

Finally, export the changed data to a CSV

exportCsv(){
new Angular5Csv(this.renderedData,'Test Report');
}

More details about the exporter can be found here: https://www.npmjs.com/package/angular5-csv

I hope this helps :)

like image 50
Kav Khalsa Avatar answered Sep 22 '22 07:09

Kav Khalsa


You can use mat-table-exporter. To access the "export" method in the typescript code:

@ViewChild("exporter") exporter! : MatTableExporterDirective;

<table mat-table matTableExporter [dataSource]="dataSource" 
                               #exporter="matTableExporter">
like image 41
stlukas1 Avatar answered Sep 24 '22 07:09

stlukas1