Export data in CSV format on Button onClick in Angular 2+ using ngx-csv
Introduction
ngx-csv is a Helper library to create a CSV file in an angular 2+ project. Adding (ngx-csv) packages to your project, you access to Export data in CSV format.
Initiating a New Angular project
Let’s get started with a new angular project with the help of ANGULAR CLI.
Create an Angular project using the command line:
$ ng new ngxcsv
This command is now downloading all dependencies & default angular project with a template.
Installing ngx-csv
Now we adding ngx-csv as a dependency library in angular project.
command line for installing ngx-csv
1: $ npm i ngx-csv
Now we can start using ngx-csv in our angular project
How to export Table data in csv format on button onClick 😊
First we all need to import ngx-csv in our component.ts file.
Lets create a table in our template file (app.component.html)
1 :- app.component.ts
<button type=”button” class=”btn btn-success” (click)=”results()”>Export csv</button>
<h2>Table </h2>
<table>
<tr>
<th>Country</th>
<th>Population</th>
<th>Language</th>
</tr>
<tr *ngFor=”let data of data”>
<td>{{data.country}}</td>
<td>{{data.population}}</td>
<td>{{data.language}}</td>
</tr>
</table>
2 :- app.component.ts
import { Component, OnInit } from ‘@angular/core’;
import { ngxCsv } from ‘ngx-csv/ngx-csv’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit {
data = [
{
country: “India”,
population: 1.35 billion,
language: No specific language,
},
{
country: ‘China’,
population: 1.45 billion,
language: Mandarin,
},
{
country: ‘England’,
population: 5.5 million,
language: English,
},
];
constructor() { }
ngOnInit() {}
results(){
new ngxCsv(this.data, ‘My Report’);
}
}
Now Button onClick we’ll get CSV file like below
Conclusion
Hope you find these articles helpful.cheers guys 😊
How to Show data in a table using Http get method from a web API with search filter & pagination
https://sunelika1.blogspot.com/2020/07/show-data-in-table-using-http-get.html
Comments
Post a Comment