Export JSON to CSV file in Angular

In this Article, we will learn How to convert a JSON array into CSV and How to Export CSV as a downloadable file by using Blob in angular 8.

Demo: https://stackblitz.com/edit/angular8-json-to-csv

Step1: Converting JSON to CSV
For converting JSON data in to CSV format use the follwing method.

filter_none

edit
close

play_arrow

link
brightness_4
code

ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    let str = '';
    let row = 'S.No, ';
    for (let index in headerList) {
        row += headerList[index] + ', ';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i & lt; array.length; i++) {
        let line = (i + 1) + & #039;&# 039;;
        for (let index in headerList) {
            let head = headerList[index];
            line += & #039;, &# 039; + array[i][head];
        }
        str += line + & #039;\r\n&# 039;;
    }
    return str;
}

chevron_right


The first parameter is Array of Objects, and second parameter is the headers List generally the keys of Json.

Step2: Exporting CSV as a downloadable file.
For exporting CSV data as a .csv file use the follwing method.

filter_none

edit
close

play_arrow

link
brightness_4
code

downloadFile(data, filename = 'data') {
    let csvData = this.ConvertToCSV(data, [
      'name', 'age', 'average', 'approved', 'description']);
    console.log(csvData)
    let blob = new Blob(['\ufeff' + csvData], {
        type: 'text/csv;charset=utf-8;'
    });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf(
      'Safari') != -1 & amp; & amp;
    navigator.userAgent.indexOf('Chrome') == -1;
    
    //if Safari open in new window to save file with random filename.
    if (isSafariBrowser) { 
        dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", filename + ".csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
}

chevron_right


The download method accepts two parameters, the first parameter in JSONdata and the second parameter is filename. the default file name here is data. In the downloadFile method we are calling ConvertToCSV method which converts the JSON to CSV.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user’s system.

app.service.ts: Create a new service file with name app.component.ts

filter_none

edit
close

play_arrow

link
brightness_4
code

import {
    Injectable
}
from '@angular/core';
@Injectable()
export class AppService {
    downloadFile(data, filename = 'data') {
        let csvData = this.ConvertToCSV(data, [
            'name', 'age', 'average', 'approved', 'description'
        ]);
        console.log(csvData)
        let blob = new Blob(['\ufeff' + csvData], {
            type: 'text/csv;charset=utf-8;'
        });
        let dwldLink = document.createElement("a");
        let url = URL.createObjectURL(blob);
        let isSafariBrowser = navigator.userAgent.indexOf(
            'Safari') != -1 & amp; & amp;
        navigator.userAgent.indexOf('Chrome') == -1;
        /if Safari open in new window to save file with random filename.
        if (isSafariBrowser) {
            /
            dwldLink.setAttribute("target", "_blank");
        }
        dwldLink.setAttribute("href", url);
        dwldLink.setAttribute("download", filename + ".csv");
        dwldLink.style.visibility = "hidden";
        document.body.appendChild(dwldLink);
        dwldLink.click();
        document.body.removeChild(dwldLink);
    }
    ConvertToCSV(objArray, headerList) {
        let array =
            typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        let str = '';
        let row = 'S.No, ';
        for (let index in headerList) {
            row += headerList[index] + ', ';
        }
        row = row.slice(0, -1);
        str += row + '\r\n';
        for (let i = 0; i & lt; array.length; i++) {
            let line = (i + 1) + & #039;&# 039;;
            for (let index in headerList) {
                let head = headerList[index];
                line += & #039;, &# 039; + array[i][head];
            }
            str += line + & #039;\r\n&# 039;;
        }
        return str;
    }
}

chevron_right


Now we have our service file, use this service file in our component to send the data and check whether our downloadFile method is properly working or not. Before creating component, first import our service in app.module.ts

app.module.ts:

filter_none

edit
close

play_arrow

link
brightness_4
code

import { AppService } from './app.service';
@NgModule({
  providers: [AppService],
})</pre>
  
<h5>app.component.ts:-</h5>
<pre>
import { Component } from '@angular/core';
import { AppService } from './app.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
constructor(private appService:AppService) {  }
  jsonData =  [
      {
        name: "Anil Singh",
        age: 33,
        average: 98,
        approved: true,
        description: "I am active blogger and Author."
      },
      {
        name: 'Reena Singh',
        age: 28,
        average: 99,
        approved: true,
        description: "I am active HR."
      },
      {
        name: 'Aradhya',
        age: 4,
        average: 99,
        approved: true,
        description: "I am engle."
      },
    ];
  download(){
    this.appService.downloadFile(this.jsonData, 'jsontocsv');
  }
}

chevron_right


Output: app.component.html file



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.