Export JQGrid data to Excel using javascript

10,378

Solution 1

You can use $("#reportGrid").jqGrid("getGridParam", "colNames") to get column headers.

By the way you can use jQuery.extend to make copy of the data, returned from $("#reportGrid").jqGrid("getGridParam", "data"), and then modify the data before calling of JSONToCSVConvertor.

UPDATED: The object which you get by $("#reportGrid").jqGrid("getGridParam", "data") is the reference to internal data parameters. So it contains all what it should contains. To have less properties in the items of the data you should first make a copy of the object and the modify it like you want. For example to delete Id property from all items of the data you can do the following:

var myData = $.extend(true, [],
        $("#reportGrid").jqGrid("getGridParam", "data"));
$.each(myData, function () { delete this.Id; });

UPDATED: One can use SheetJS, for example, to export data to Excel. See the demo https://jsfiddle.net/OlegKi/ovq05x0c/6/, created for the issue. The corresponding code of the Export to Excel button used in the demo is the following

.jqGrid("navButtonAdd", {
    caption: "",
    title: "Export to Excel(.XLSX)",
    onClickButton: function () {
        var data = $(this).jqGrid("getGridParam", "lastSelectedData"), i, item,
            dataAsArray = [
                ["Client", "Date", "Amount", "Tax", "Total", "Closed", "Shipped via"]
            ];

        for (i = 0; i < data.length; i++) {
            item = data[i];
            dataAsArray.push([
                item.name, new Date(item.invdate),
                item.amount, item.tax, item.total,
                item.closed, item.ship_via
            ]);
        }

        var ws_name = "SheetJS", filename = "jqGrid.xlsx";
        var wb = XLSX.utils.book_new(),
            ws = XLSX.utils.aoa_to_sheet(dataAsArray);
        XLSX.utils.book_append_sheet(wb, ws, ws_name);
        XLSX.writeFile(wb, filename);
    }
});

Solution 2

Thanks to Oleg and the man who posted http://jsfiddle.net/hybrid13i/JXrwM/ with little enhancement in it this is my final solution

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel,headers,excludeColumns,
    fileName) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

var CSV = '';    
//Set Report title in first row or line

CSV += ReportTitle + '\r\n\n';

//This condition will generate the Label/Header
if (ShowLabel) {
    var row = "";

    if(headers)
    {
        row = headers.join(',');
    }
    else
    {
        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {         
            //Now convert each value to string and comma-seprated
            row += index + ',';
        }
    }
    row = row.slice(0, -1);     

    //append Label row with line break
    CSV += row + '\r\n';
}

//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
    var row = "";

    //2nd loop will extract each column and convert it in string comma-seprated
    for (var colName in arrData[i]) {
        if(excludeColumns && excludeColumns.indexOf(colName))
            continue;
        row += '"' + arrData[i][colName] + '",';
    }

    row.slice(0, row.length - 1);

    //add a line break after each row
    CSV += row + '\r\n';
}

if (CSV == '') {        
    alert("Invalid data");
    return;
}   

if(!fileName)
{
    //Generate a file name
     fileName = "MyReport_";
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName += ReportTitle.replace(/ /g,"_");   
}

if (navigator.appName == "Microsoft Internet Explorer") {    
    var oWin = window.open();
    oWin.document.write('sep=,\r\n' + CSV);
    oWin.document.close();
    oWin.document.execCommand('SaveAs', true, fileName + ".csv");
    oWin.close();
  }  
else
{

    //Initialize file format you want csv or xls
    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    // Now the little tricky part.
    // you can use either>> window.open(uri);
    // but this will not work in some browsers
    // or you will not get the correct file extension    

    //this trick will generate a temp <a /> tag
    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);
 }
   }

Usage:

    JSONToCSVConvertor($(grid).jqGrid("getGridParam", "data"), $("#reportHeader").text().trim(),true,$(grid).jqGrid("getGridParam", "colNames"),["_id_"],"Report");

NOTE Please note that this solution will not work in IE

Share:
10,378
Haider
Author by

Haider

Updated on June 14, 2022

Comments

  • Haider
    Haider almost 2 years

    I want to download the grid data in csv format , by looking at the link http://jsfiddle.net/hybrid13i/JXrwM/ and using JSONToCSVConvertor($("#reportGrid").jqGrid("getGridParam", "data"),"Report",true);

    you can download a csv file but its column name are variable names not label any idea how can i fix this , or there is another solution

  • Haider
    Haider about 9 years
    Thanks for you answer i changed in the function see if it can be improved
  • Ajoe
    Ajoe almost 7 years
    Is it possible to add a style to the csv like header bold, borders etc