使用jQuery或jqGrid导出到Excel

6
我有一个jqGrid,从服务器(Java)以JSON格式一次性获取数据。我希望将jqGrid中的数据导出为Excel格式。
到目前为止,我看到了这个页面,在IE中会出现错误'o.url is null or not an object' grid.import.js 我还看到了这个演示,其中导出按钮的工具提示显示Export To Excel,但保存的文件却是xml格式。
因此,我希望得到任何建议,可以使用javascript或jquery插件将我的JSON字符串转换为Excel,或者使用jqgrid的内置功能。
我的jqGrid enter image description here 我的jqGrid代码
grid = jQuery("#list2");
                grid.jqGrid({
                    datastr : comparePatchData,
                    datatype: 'jsonstring',
                    colNames:['Name',starheader, header1, header2],
                    colModel:[
                        {name:'elementName',index:'elementName', width:90},
                        {name:'isPrasentinXml1',index:'isPrasentinXml1', width:100, align:'center', formatter: patchPresent},
                        {name:'isPrasentinXml2',index:'isPrasentinXml2', width:100, align:'center', formatter: patchPresent},
                        {name:'isPrasentinXml3',index:'isPrasentinXml3', width:100, align:'center', formatter: patchPresent}
                    ],
                    pager : '#gridpager2',
                    rowNum:12,
                    scrollOffset:0,
                    height: 320,
                    autowidth:true,
                    viewrecords: true,
                    gridview: true,
                    loadonce:true,
                    jsonReader: {
                        repeatitems: false,
                        page: function() { return 1; },
                        root: "response"
                    },
                    subGrid: true,
                    // define the icons in subgrid
                    subGridOptions: {
                        "plusicon"  : "ui-icon-triangle-1-e",
                        "minusicon" : "ui-icon-triangle-1-s",
                        "openicon"  : "ui-icon-arrowreturn-1-e",
                        //expand all rows on load
                        "expandOnLoad" : false
                    },

                    subGridRowExpanded: function(subgrid_id, row_id) {
                        //console.info(subgrid_id+", "+row_id);
                        var subgrid_table_id, pager_id, iData = -1;
                        subgrid_table_id = subgrid_id+"_t";
                        //pager_id = "p_"+subgrid_table_id;
                        $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' style='overflow-y:auto' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");

                        $.each(comparePatchData.response,function(i,item){
                            if(item.id === row_id) {
                                iData = i;
                                return false;
                            }

                        });
                        if (iData == -1) {
                            return; // no data for the subgrid
                        }

                        jQuery("#"+subgrid_table_id).jqGrid({
                            datastr : comparePatchData.response[iData],
                            datatype: 'jsonstring',
                            colNames: ['Name','Value1','Value2','Value3'],
                            colModel: [
                                {name:"name",index:"name",width:90},
                                {name:"firstValue",index:"firstValue",width:100},
                                {name:"secondValue",index:"secondValue",width:100},
                                {name:"thirdValue",index:"thirdValue",width:100}
                            ],
                            rowNum:10,
                            //pager: pager_id,
                            sortname: 'name',
                            sortorder: "asc",
                            height: 'auto',
                            autowidth:true,
                            jsonReader: {
                                repeatitems: false,
                                //page: function() { return 1; },
                                root: "attribute"
                            }
                        });

                        jQuery("#"+subgrid_table_id).jqGrid('navGrid',{edit:false,add:false,del:false});
                    }
                });
                grid.jqGrid('navGrid','#gridpager2',{add:false,edit:false,del:false});
                grid.jqGrid('navButtonAdd','#gridpager2',{
                    caption:"Export to Excel", 
                    onClickButton : function () { 
                        jQuery("#list2").excelExport();
                    } 
                });

我的Json的一部分

{
"response": [
    {
        "id": "1",
        "elementName": "libgtop2-devel-2.14.4-3.el5",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": false,
        "isPrasentinXml2": false,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "thirdValue": "libgtop2-devel-2.14.4-3.el5"
            }
        ]
    },
    {
        "id": "2",
        "elementName": "ifd-egate-0.05-15",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": false,
        "isPrasentinXml2": false,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "thirdValue": "ifd-egate-0.05-15"
            }
        ]
    },
    {
        "id": "3",
        "elementName": "libXScrnSaver-devel-1.1.0-3.1",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": false,
        "isPrasentinXml2": false,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "thirdValue": "libXScrnSaver-devel-1.1.0-3.1"
            }
        ]
    },
    {
        "id": "4",
        "elementName": "kde-i18n-Chinese-Big5-3.5.4-1",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "firstValue": "kde-i18n-Chinese-Big5-3.5.4-1",
                "secondValue": "kde-i18n-Chinese-Big5-3.5.4-1"
            }
        ]
    },
    {
        "id": "5",
        "elementName": "cpio-2.6-20",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "firstValue": "cpio-2.6-20",
                "secondValue": "cpio-2.6-20",
                "thirdValue": "cpio-2.6-20"
            }
        ]
    },
    {
        "id": "6",
        "elementName": "grep-2.5.1-54.2.el5",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "firstValue": "grep-2.5.1-54.2.el5",
                "secondValue": "grep-2.5.1-54.2.el5",
                "thirdValue": "grep-2.5.1-54.2.el5"
            }
        ]
    },
    {
        "id": "7",
        "elementName": "avahi-compat-libdns_sd-0.6.16-1.el5",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "firstValue": "avahi-compat-libdns_sd-0.6.16-1.el5",
                "secondValue": "avahi-compat-libdns_sd-0.6.16-1.el5",
                "thirdValue": "avahi-compat-libdns_sd-0.6.16-1.el5"
            }
        ]
    },
    {
        "id": "8",
        "elementName": "gpm-devel-1.20.1-74.1",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "firstValue": "gpm-devel-1.20.1-74.1",
                "secondValue": "gpm-devel-1.20.1-74.1",
                "thirdValue": "gpm-devel-1.20.1-74.1"
            }
        ]
    },
    {
        "id": "9",
        "elementName": "esc-1.0.0-39.el5",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": false,
        "isPrasentinXml2": false,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "thirdValue": "esc-1.0.0-39.el5"
            }
        ]
    },
    {
        "id": "10",
        "elementName": "kde-i18n-Spanish-3.5.4-1",
        "subCategory": "patch",
        "isEqual": false,
        "isPrasentinXml1": true,
        "isPrasentinXml2": true,
        "isPrasentinXml3": true,
        "attribute": [
            {
                "name": "name",
                "firstValue": "kde-i18n-Spanish-3.5.4-1",
                "secondValue": "kde-i18n-Spanish-3.5.4-1"
            }
        ]
    }
]
}

1
例如请看这里这里 - Oleg
4个回答

6

您不必使用Excel格式导出文件才能将数据导入Excel。通常更容易导出为CSV格式。CSV文件应该默认与Excel相关联,因此它应该具有Excel图标和其他一些东西。我认为XML也可以这样做,但是在这种情况下,CSV格式更轻便,并且可以完成相同的工作。将JSON转换为CSV很简单:

var response = JSON.parse(responseJSON).response;
var csv = arrayToCSV(response);

function arrayToCSV(arr) {
    var columnNames = [];
    var rows = [];
    for (var i=0, len=arr.length; i<len; i++) {
        // Each obj represents a row in the table
        var obj = arr[i];
        // row will collect data from obj
        var row = [];
        for (var key in obj) {
            // Don't iterate through prototype stuff
            if (!obj.hasOwnProperty(key)) continue;
            // Collect the column names only once
            if (i === 0) columnNames.push(prepareValueForCSV(key));
            // Collect the data
            row.push(prepareValueForCSV(obj[key]));
        }
        // Push each row to the main collection as csv string
        rows.push(row.join(','));
    }
    // Put the columnNames at the beginning of all the rows
    rows.unshift(columnNames.join(','));
    // Return the csv string
    return rows.join('\n');
}

// This function allows us to have commas, line breaks, and double 
// quotes in our value without breaking CSV format.
function prepareValueForCSV(val) {
    val = '' + val;
    // Escape quotes to avoid ending the value prematurely.
    val = val.replace(/"/g, '""');
    return '"' + val + '"';
}

我有了 csv 文件后,接下来该怎么把它放入文件中呢? - AabinGunz
这是无法在客户端完成的。您需要创建一个服务器端脚本来实现。您在服务器上使用什么? - benekastah
1
啊,可惜我不太熟悉Java,无法快速回答如何将CSV转换为文件。这个JavaScript函数可以将CSV文件的内容以字符串形式返回,你可以将其发送到服务器端代码以从中创建一个文件。 - benekastah
晚了点,但我不完全同意你的评论“同样有价值”。使用CSV时,由于小数和日期格式的原因,必须注意区域设置。使用Excel可以以类型安全的方式工作。 - Gert Arnold
@GertArnold 确实。已删除上面的“同等有价值”的声明。 - benekastah

0

0

我是这样解决的:

  1. 阅读

https://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/#Installation

  • 这里是Github
  • https://github.com/kayalshri/tableExport.jquery.plugin

    这是一个演示

    http://demos.w3lessons.info/jquery-table-export#

    它完美地工作了,我尝试了导出Excel功能。 在我的情况下,我只是使用了jqgrid表的id选择器。

    顺便说一句,这将仅导出可见部分,因此如果您有100页,则需要服务器端,因为信息不在那里!。


    -2

    我正在使用MOSS 2007将一些列表(比如5个列表)导出到Excel。我的要求是需要将多个列表导出到Excel中。我在页面中添加了一个CEWP和一个按钮,以便通过单击一次即可将多个列表数据导出到Excel中。但是当我使用jQuery时,我遇到了运行时错误。 如果($('#WebPartWPQ3').is(':visible'))--->对象预期的错误。 我找不到任何div id来跟踪...所以有人知道答案,请帮忙解决。 与此问题相关的答案真的非常非常非常感激..我的代码如下。



    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接