Search code examples
javascriptcsvjqgrid

Export JQGrid data to Excel using javascript


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


Solution

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