0

Export JSON Data to CSV File in AngularJs based on ui-grid's every row id

I need a CSV export option in angularjs 1.0 UI-grid's every row, where the user will click on that button, and based on the id server will respond a JSON based data then it should download in CSV format.

See the below image with Export CSV button.

enter image description here

Here's what I have tried so far:

Grid's column Definition

         {
             field: "actions", "name": "Action",
             cellTemplate: '<button type="button" field-separator=","  ng-click="funcExport({{row.entity._id}})" csv-header="exportHeader" ng-csv="export" filename="Sample.csv">Export CSV</button>',
             width: "170"
         }

Export Function To CSV: Currently JSON data is not based on id but in static for demonstration.

    /*Function to export*/
var funcExport = function (id) {
    $scope.exportarray = [];
    $scope.exportHeader = [];
    $scope.export = [];
    $scope.exportHeader = ['Licence', 'Condition'];

    $scope.exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];

    $scope.export = $scope.exportarray;
}

Any help would be appreciated!!

2 Answers 2

1

First convert JSON to comma separated CSV string then crate an anchor tag(a) set this CSV string as href fire a click, remove anchor tag.

function convertToCSV(array) {

    var str = '';

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

function exportCSVFile(headers, items, fileTitle) {

    items.unshift(headers);

    var csv = convertToCSV(items);
    var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", exportedFilenmae);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

/*Function to export*/
var funcExport = function (id) {

    var exportHeader = ['Licence', 'Condition'];

    var exportarray = [{ "Licence": "229973", "Condition": "Usage" }, { "Licence": "24141", "Condition": "Level" }];

    exportCSVFile(exportHeader , exportarray, 'download' );

}

This code was taken from here

Sign up to request clarification or add additional context in comments.

2 Comments

In exportCSVFile method undefined jsonObject, in convertToCSV method missing parsing of objArray, missing fileTitle parameter to exportCSVFile method. However, i worked around your reference and that worked like a charm!! Thankx!!
Sorry, I had copied those code and tried to cleanup and without running posted here. That caused those errors. I've updated my code. You are welcome.
0

Here's a working solution

convert a Javascript array of object to CSV

function convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

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

Export to CSV Function

function exportCSVFile(headers, items, fileTitle) {
     if (headers) {
        items.unshift(headers);
    }
    // Convert Object to JSON
    var jsonObject = JSON.stringify(items);

    var csv = convertToCSV(jsonObject);
    var exportedFilenmae = fileTitle + '.csv' || 'wal_export.csv';

    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", exportedFilenmae);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

Function to be called in a ui-grid row

$scope.funcExport = function (row) {
        var id = row.entity._id;//this will be used for dynamic data later
        var exportHeader = ['Licence', 'Condition'];
        var headers = {
            licence: 'Licence'.replace(/,/g, ''), // remove commas to avoid errors
            condition: "Condition"
        };
        var exportarray = [
                            { "licence": "229973", "condition": "Usage" }, 
                            { "licence": "24141", "condition": "Level" }
                          ];

        var fileTitle = 'WAL_CSV'; // or 'my-unique-title'
        exportCSVFile(headers, exportarray, fileTitle);

    }

Finally, ui-grid's column definition

{
   field: "actions", "name": "Action",                 
   cellTemplate: '<a ng-click="grid.appScope.funcExport(row)"> Download {{row.entity.LicenceType}} CSV </a>',                
   width: "170"
 }

The solution is based on Danny Pule Export JSON to CSV file using Javascript (in the browser).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.