There are 2 ways to export(download) the CSV on the web.
- Generate at the server-side and then provide a link to download
- Generate at client-side through angular
So today we will discuss the client-side through angular
Installation
We will use angular2-csv
package to generate the CSV at the client-side(browser)
Please run this command at your project root
npm install --save angular2-csv
Setup
Please include the below code in you app.module.ts
and in the child module where you want to implement the download functionality
// file name app.module.ts import { Angular2CsvModule } from 'angular2-csv';
- Add in imports section of the app.module.ts file
imports: [ BrowserModule, AppRoutingModule, Angular2CsvModule ],
- Add the download button
In your app.component.html
file or your html file where you want to add the download button,
<angular2csv [data]="data" filename="test.csv" [options]="options"></angular2csv>
- in your app.component.ts
add this or you can replace by it
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { // option veriable options = { fieldSeparator: ',', quoteStrings: '"', decimalseparator: '.', showLabels: false, headers: [], showTitle: true, title: 'asfasf', useBom: false, removeNewLines: true, keys: ['approved','age','name' ] }; // This data will be generated in the csv file data = [ { name: "Test, 1", age: 13, average: 8.2, approved: true, description: "using 'Content here, content here' " }, { name: 'Test 2', age: 11, average: 8.2, approved: true, description: "using 'Content here, content here' " }, { name: 'Test 3', age: 10, average: 8.2, approved: true, description: "using 'Content here, content here' " } ]; }
Demo
You can check the demo from Here and can get the code from the Github repo
Please give it a try and I will be happy to answer your queries on my Twitter handle Twitter
Top comments (0)