You are currently viewing Using Angular2 to Convert JSON to CSV
using-angular2-to-convert-json-to-csv

Using Angular2 to Convert JSON to CSV

  • Post published:September 16, 2016

vteam #492 was required to export CSV for the displayed lists of orders and companies at the front-end of a business development agency using Angular2. A custom solution had to be developed as Angular2 doesn’t provide a functionality to meet this requirement. Previously, the agency portal was getting JSON from Laravel web service API.

To perform this operation, there was only one dependency i.e. the Reactive Extensions for JavaScript (rxjs) library. This library had to be imported at the Header of the Component file using the following command:

import 'rxjs/Rx';

After that, the following steps were implemented:

  • The data was fetched from web service API using ngOnInit() function, so that it would be available everywhere in that component
  • Used Class Variable so that it could be manipulated easily
  • Created a function for “download” that would be needed to call for a Click to download file (in the sample code below, we named the function as “download“)
  • Created a function that would convert the JSON object to comma-Separated String (in sample code, we named that function as “ConvertToCSV“)
  • After the conversion in download function, the whole data would be then stored as a BLOB and written in a file
    .
// Download CSV Sample Code
download(){
    var csvData = this.ConvertToCSV(this.data);
    var blob = new Blob([csvData], { type: 'text/csv' });
    var url= window.URL.createObjectURL(blob);
    window.open(url);
}

It was working fine in Firefox browser. But, in Chrome, it was displaying like a text file without any File Extension. vteams engineer Aqeel Shamas did some work around to fix this issue:

  1. Created an anchor tag at the end of the HTML body
  2. Made that anchor tag as Hidden after adding Blob data in that particular ObjectURL
  3. Triggered Click Event for that particular Anchor Tag automatically
  4. HTML5 provided a new property “download” for anchor tag, which is being used to download a source forcefully. This “download” property was then added to that newly created anchor tag
    .

Following is the sample code for downloading CSV function:

// Final Code for Download CSV Function
download(){
    var csvData = this.ConvertToCSV(this.data);
    var a = document.createElement("a");
    a.setAttribute('style', 'display:none;');
    document.body.appendChild(a);
    var blob = new Blob([csvData], { type: 'text/csv' });
    var url= window.URL.createObjectURL(blob);
    a.href = url;
    a.download = 'SampleExport.csv';
    a.click();
}

Note: If an error occurs in your editor for “a.download = ‘SampleExport.csv’;“, just ignore it. It will work fine. The following code will convert the JSON to comma-separated string:

// convert Json to CSV data in Angular2
    ConvertToCSV(objArray) {
            var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
            var str = '';
            var row = "";

            for (var index in objArray[0]) {
                //Now convert each value to string and comma-separated
                row += index + ',';
            }
            row = row.slice(0, -1);
            //append Label row with line break
            str += row + '\r\n';

            for (var i = 0; i < array.length; i++) {
                var line = '';
                for (var index in array[i]) {
                    if (line != '') line += ','

                    line += array[i][index];
                }
                str += line + '\r\n';
            }
            return str;
        }