Open In App

Export JSON to CSV file in Angular

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to convert a JSON array into CSV and How to Export CSV as a downloadable file by using Blob in angular 8. The below approach will be followed.

Steps to Export the JSON to CSV File

Step 1: Converting JSON to CSV

For converting JSON data into CSV format using the following method. The first parameter is the Array of Objects, and the second parameter is the headers List generally the keys of JSON. 

Javascript




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) + "";
        for (let index in headerList) {
            let head = headerList[index];
            line += ',' + array[i][head];
        }
        str += line + "\r\n";
    }
    return str;
}


Step 2: Exporting CSV as a downloadable file. For exporting CSV data as a .csv file use the following method. 

Javascript




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 &&
        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);
}


The download method accepts two parameters, the first parameter is JSONdata, and the second parameter is the filename. the default file name here is data. In the downloadFile method, we are calling the 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 the name app.service.ts 

Javascript




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 && navigator.userAgent.indexOf('Chrome') == -1;
        if (isSafariBrowser) {
 
            // If Safari open in new window to
            // save file with random filename.
            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 < array.length; i++) {
            let line = (i + 1) + '';
            for (let index in headerList) {
                let head = headerList[index];
                line += ',' + array[i][head];
            }
            str += line + '\r\n';
        }
        return str;
    }
}


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

  • app.component.ts: 

javascript




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');
    }
}


  • app.component.html

HTML




<div style="text-align: center">
    <h1 style="color: green">
          GeeksforGeeks
      </h1>
    <h3>
      Convert Json to CSV file and
      Download it in the .csv format
      </h3>
    <button (click)="download()">
          Download
      </button>
</div>


  • app.module.ts:

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule }
    from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
 
@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    providers: [AppService],
    bootstrap: [AppComponent]
})
export class AppModule { }


Output:

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



Last Updated : 18 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads