Generate or Export data to CSV with headers in Angular 2/4/5/6

First of all you need to install angular2-csv library by following below command

Run the following command in command prompt

> npm install --save angular2-csv

Create a component name it as 'pdfcomponent'

> ng g component 'csvcomponent'

In csvcomponent.component.html page add the follwoing code:

 <button (click)="download()">download/export</button>

In csvcomponent.component.ts page add the follwoing code:

import { Component, OnInit } from '@angular/core';
import { Angular2Csv } from 'angular2-csv/Angular2-csv';
import { UserService } from '../_services/index';

selector: 'app-csv',
templateUrl: './csv.component.html',
styleUrls: ['./csv.component.css']
export class CsvComponent implements OnInit {

private allItems: {};
constructor(private csvService: CsvService) { }

ngOnInit() {

download() {
.subscribe(data => {
//API data
this.allItems = data.result.users;

/*var TestStaticData = [
first_name: "srinivas",
last_name: "arevarapu",
id: 11
first_name: "anji",
last_name: "arevarapu",
id: 12

var options = {
fieldSeparator: ',',
quoteStrings: '"',
decimalseparator: '.',
showLabels: true,
showTitle: true,
headers: ['First Name','Last Name','ID']
new Angular2Csv(this.allItems, 'TestCsv Report',options);
//new Angular2Csv(TestStaticData, 'TestCsv Report',options);

About Author: author 4 + years of Information Technology experience in understanding and analyzing the software and hardware engineering requirements, onsite and offshore management of product development. Expert work on design and development for windows,web,mobile Expert knowledge of C#,ADO.NET, ASP.Net MVC, ENTITY FRAMEWORK, LINQ,COLLECTIONS, JAVASCRIPT,AngularJs 1.0,Angular2, Jquery,Jquery-Ajax, SQL SERVER, XAML,Windows phone 8.1 Good knowledge of WCF-Restful services,WCF, WEB API-Services ,Web- Services,MIcrosoft-Azure,JUICE UI,HTML,CSS,AJAX Read More...

Join him on Google+ | Facebook | Linkedin

No comments