使用javascript将JQGrid数据导出到Excel

问题描述 投票:2回答:2

我想通过查看链接http://jsfiddle.net/hybrid13i/JXrwM/并使用JSONToCSVConvertor($("#reportGrid").jqGrid("getGridParam", "data"),"Report",true);以csv格式下载网格数据

你可以下载一个csv文件但它的列名是变量名不标记任何想法如何解决这个问题,或者有另一个解决方案

javascript csv jqgrid
2个回答
4
投票

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

顺便说一句,你可以使用jQuery.extend来复制数据,从$(“#reportGrid”)。jqGrid(“getGridParam”,“data”)返回,然后在调用JSONToCSVConvertor之前修改数据。

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

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

更新:例如,可以使用SheetJS将数据导出到Excel。查看为https://jsfiddle.net/OlegKi/ovq05x0c/6/创建的演示the issue。演示中使用的导出到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);
    }
});

1
投票

感谢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

© www.soinside.com 2019 - 2024. All rights reserved.