Welcome folks today in this blog post we will be using the ngx-csv
library to export json to csv
file and download it inside the browser using typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you need to install the below libraries
using the below command as shown below
npm i ngx-csv
And after that you will see the below directory
structure of the angular app as shown below
And now we need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 4 5 6 |
<ul *ngFor="let d of data"> <li>{{d.name}}</li> <li>{{d.age}}</li> <li>{{d.country}}</li> </ul> <button (click)="downloadCSV()">Download CSV</button> |
As you can see in the above html
code we are displaying the json
array of objects inside the ul
tag and here we are using the ngFor
directive to use the for
loop to display the name
age and country. And then we have the button to export the json
to csv
file using the ngx-csv
library as shown below.
And now we need to go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import { Component } 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 { title="export to csv" data = [ { name:'John Williamson', age:25, country:'New Zealand' }, { name:'Trent Boult', age:27, country:'New Zealand' }, { name:'Devon Conway', age:32, country:'New Zealand' }, { name:'Tim Southee', age:29, country:'New Zealand' } ]; downloadCSV() { var options = { title: 'User Details', fieldSeparator: ',', quoteStrings: '"', decimalseparator: '.', showLabels: false, noDownload: false, showTitle: false, useBom: false, headers:['Name','Age','Country'] }; new ngxCsv(this.data, "report", options); } } |
As you can see in the above typescript
code we are importing the ngx-csv
module at the top and then we are declaring the json
object in which we are storing the user details. And inside the downloadCSV()
method we are declaring the options where we are providing the headers
of the csv file and then we are using the ngxCsv()
constructor to pass the json
data and then we are providing the name
of the csv file and we are providing the options.