使用 javascript 将 JQGrid 数据导出到 Excel

Export JQGrid data to Excel using javascript

我想下载 csv 格式的网格数据,方法是查看 link http://jsfiddle.net/hybrid13i/JXrwM/ 并使用 JSONToCSVConvertor($("#reportGrid").jqGrid("getGridParam", "data"),"Report",true);

您可以下载一个 csv 文件,但它的列名是变量名而不是标签不知道我该如何解决这个问题,或者还有其他解决方案

您可以使用 $("#reportGrid").jqGrid("getGridParam", "colNames") 获取列 headers。

顺便说一下,您可以使用 jQuery.extend 复制从 $("#reportGrid").jqGrid("getGridParam", "data") 返回的数据,然后修改数据调用JSONToCSVConvertor.

之前

更新: 你通过 $("#reportGrid").jqGrid("getGridParam", "data") 得到的 object 是对内部 [=16] 的 reference =] 参数。所以它包含了它应该包含的所有内容。要在数据项中减少属性,您应该首先 复制 object 的副本 并根据需要对其进行修改。例如,要从所有数据项中删除 Id 属性,您可以执行以下操作:

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

已更新:可以使用 SheetJS, for example, to export data to Excel. See the demo https://jsfiddle.net/OlegKi/ovq05x0c/6/, created for the issue。 demo中使用的Export to Excel按钮对应的代码如下

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

感谢 Oleg 和发帖的人 http://jsfiddle.net/hybrid13i/JXrwM/ 这是我最终的解决方案

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

用法:

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

注意 请注意,此解决方案不适用于 IE