DEV Community

Cover image for How to export CSV file in angular
eavnitech
eavnitech

Posted on • Updated on • Originally published at eavnitech.com

How to export CSV file in angular

There are 2 ways to export(download) the CSV on the web.

  1. Generate at the server-side and then provide a link to download
  2. 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
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

- Add in imports section of the app.module.ts file

imports: [
  BrowserModule,
  AppRoutingModule,
  Angular2CsvModule
],
Enter fullscreen mode Exit fullscreen mode

- 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>
Enter fullscreen mode Exit fullscreen mode

- 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' "
    }
  ];
}
Enter fullscreen mode Exit fullscreen mode

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)