kiran
kiran

Reputation: 11

how to skip first row and add heading to download csv file

This is my code:

<script type="text/javascript">  
    functionExport(json_data, "User_Report", true);

    function functionExport(JSONData, ReportTitle, ShowLabel) {
        var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
        var CSV = '';
        if (ShowLabel) {
            var row = "";
            for (var index in arrData[0]) {
                row += index.toUpperCase() + ',';
            }
            row = row.slice(0, -1);

            CSV += row + '\r\n';
        }
        //1st loop is to extract each row
        for (var i = 0; i < arrData.length; i++) {
            var row = "";
            for (var index in arrData[i]) {
                row += '"' + $('<div>').html(arrData[i][index]).text() + '",';

            }
            row.slice(0, row.length - 1);
            CSV += row + '\r\n';
        }
        if (CSV == '') {
            alert("Invalid data");
            return;
        }
        //Generate a file name
        var fileName = "Manage_";

        fileName += ReportTitle.replace(/ /g, "_");
        var link = document.createElement("a");
        link.href = uri;
        //set the visibility hidden so it will not effect on your web-layout
        link.style = "visibility:hidden";
        link.download = fileName + ".csv";
        //this part will append the anchor tag and remove it after automatic click
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>

Upvotes: 0

Views: 4014

Answers (2)

Fabio Beltramini
Fabio Beltramini

Reputation: 2511

My suggestion, don't reinvent the wheel. CSV's have a lot of gotcha's. Just use a library that already exists, papaparse.

Here's the function to take a JSON object and turn it into a CSV: http://papaparse.com/docs#json-to-csv

If you want to skip the first row, just pass arrData.slice(1) to it instead of arrData

If you want to add your own headers, that's what the third function signature is for... like this: Papa.unparse({fields:['a','b','c'],data:arrData})

Upvotes: 3

Ethan Fischer
Ethan Fischer

Reputation: 1489

Have you tried initializing i in your first loop to 1? Also, your jQuery selector should be $('div')

for (var i = 1; i < arrData.length; i++) {
        var row = "";
        for (var index in arrData[i]) {
            row += '"' + $('<div>').html(arrData[i][index]).text() + '",';

        }
        row.slice(0, row.length - 1);
        CSV += row + '\r\n';
    }

Upvotes: 0

Related Questions