Search code examples
javascriptangularjsexport-to-csv

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


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!!


Solution

  • 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