Javascript 在 jquery 或 jqGrid 中导出到 excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6742567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:59:58  来源:igfitidea点击:

export to excel in jquery or jqGrid

javascriptjqueryexceljquery-pluginsjqgrid

提问by AabinGunz

I have a jqGridwhere I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format.

我有一个jqGrid,我可以在其中以 JSON 格式立即从服务器 (java) 获取数据。我希望将 jqGrid 中的数据导出为 Excel 格式。

Till now I saw this pagewhich gives me an error in IE 'o.url is null or not an object' grid.import.js

直到现在我看到了这个页面,它在 IE 中给了我一个错误'o.url is null or not an object' grid.import.js

Also I saw this demowhere on the tool tip of export button it says Export To Excelbut the file saved is in xml format.

我也看到了这个演示,它在导出按钮的工具提示上说,Export To Excel但保存的文件是 xml 格式。

So I would like any suggestions that can either transform my JSON string into excel using javascript or jquery plugin or using jqgrid's inbuilt feature.

所以我想要任何可以使用 javascript 或 jquery 插件或使用 jqgrid 的内置功能将我的 JSON 字符串转换为 excel 的建议。

My jqGrid

我的 jqGrid

enter image description here

在此处输入图片说明

My jqGrid Code

我的 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();
                    } 
                });

Part of my Json

我的 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"
            }
        ]
    }
]
}

采纳答案by benekastah

You don't have to export a file using the Excel format in order to get the data into Excel. It is generally much easier to export to CSV. CSVfiles should be associated with Excel by default, so it should have the Excel icon by it and everything. XMLwould work the same way, I think, but the CSVformat is much lighter, and does the same job in this case. Converting JSONto CSVis simple:

您不必使用 Excel 格式导出文件即可将数据导入 Excel。导出到CSV. CSV默认情况下,文件应该与 Excel 关联,因此它应该有 Excel 图标和所有内容。XML我认为会以相同的方式工作,但CSV格式要轻得多,并且在这种情况下可以完成相同的工作。转换JSONCSV很简单:

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 + '"';
}

回答by Mike Gledhill

I have a jqGrid where I get data at once from server (java) in JSON format. I want the data in the jqGrid to be exported into Excel format.

我有一个 jqGrid,我可以在其中以 JSON 格式立即从服务器 (java) 获取数据。我希望将 jqGrid 中的数据导出为 Excel 格式。

Here's a nice article, showing you how to export from jqGrid to Excel...

这是一篇不错的文章,向您展示了如何从 jqGrid 导出到 Excel...

http://www.codeproject.com/Articles/784342/Export-data-from-jqGrid-into-a-real-Excel-file

http://www.codeproject.com/Articles/784342/Export-data-from-jqGrid-into-a-real-Excel-file

回答by shareef

I solved this like this:

我是这样解决的:

  1. Read

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

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

  1. Here is github
  1. 这里是github

https://github.com/kayalshri/tableExport.jquery.plugin

https://github.com/kayalshri/tableExport.jquery.plugin

  1. Here is a demo
  1. 这是一个演示

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

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

It works perfectly i tried the Export Excel. In my case i just used the id selector for the jqgrid table.

它工作得很好,我尝试了导出 Excel。在我的例子中,我只是使用了 jqgrid 表的 id 选择器。

BTWThis will export only visible part so if you 100 pages it need server side because info is just not there !.

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

回答by Dave Milner

I'm working with MOSS 2007 to export some lists(say 5 lists) to excel.My requirement is i need more than one lists to be exported to excel.I have added a CEWP in my page with a button so that by one click i can export more than one list datas to excel.nw i get a run time error when i use jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error. I dont find any div id to trace..so is anybody know the answer,pls be come out of it.. ans related to this issue is really really really appreciated..my code is as follows.

我正在使用 MOSS 2007 将一些列表(比如 5 个列表)导出到 excel。我的要求是我需要将多个列表导出到 excel。我在我的页面中添加了一个带有按钮的 CEWP,以便单击我可以将多个列表数据导出到 excel.nw 当我使用 jquery if( $('#WebPartWPQ3').is(':visible') )--->object expected error 时我得到一个运行时错误。我没有找到任何要跟踪的 div id..所以有人知道答案吗,请出来吧.. 与此问题相关的答案真的非常感谢..我的代码如下。

<button type="button"
onclick=exportToExcel();>Click<br>
</button><br>
<script type="text/javascript"><br>
 function exportToExcel() <br>
{ <br>
alert('Hi');<br>
//alert($("#WebPartWPQ3").attr("visibility"));<br>
if( $('#WebPartWPQ3').is(':visible') )<br>
{ <br>
 contentType = "application/vnd.ms-excel";<br>
var oExcel = new ActiveXObject("Excel.Application");<br>
var oBook = oExcel.Workbooks.Add;<br>
var oSheet = oBook.Worksheets(1);<br>

var VESSApplications =document.getElementById<br>('ctl00_m_g_e3f5d791_5651_40ca_a03a_1c511c7f2b28_ctl00_ctl00_toolBarTbl');<br>
  alert(document.getElementById('WebPartWPQ3'));<br>
var OtherApplications =document.getElementById('tblOtherApplications');<br>
 //   var MFGApplications =document.getElementById('tblMFGApplications');<br>
var row=3;<br>
var col=1;<br>

//Define criteria - start<br>
oSheet.Cells(row, col)="Business Function";<br>
oSheet.Cells(row, col+1)="VESS";<br>
oSheet.Cells(row, col+2)=selectedVESSBusinessFunction;<br>
 //  oSheet.Cells(row, col+3)="Manufacturing";<br>
 //  if(selectedMFGBusinessFunction != "-Select-")<br>
 //  oSheet.Cells(row, col+4)=selectedMFGBusinessFunction;<br>
row +=2;<br>

oSheet.Cells(row, col)="Operating System";<br>
oSheet.Cells(row, col+1)="First Choice";<br>
    if(selectedOperatingSystemFirstChoice != "-Select-")<br>

 oSheet.Cells(row, col+2)=selectedOperatingSystemFirstChoice;<br>


oSheet.Cells(row, col+3)="Second Choice";<br>

if(selectedOperatingSystemSecondChoice != "-Select-")<br>

oSheet.Cells(row, col+4)=selectedOperatingSystemSecondChoice;<br>

row +=2;<br>
oSheet.Cells(row, col)="Platform";<br>
oSheet.Cells(row, col+1)="First Choice";<br>
oSheet.Cells(row, col+2)=selectedPlatformFirstChoice;<br>
oSheet.Cells(row, col+3)="Second Choice";<br>

if(selectedPlatformSecondChoice != "-Select-")<br>

oSheet.Cells(row, col+4)=selectedPlatformSecondChoice;<br>
row +=2;<br>
oSheet.Cells(row, col)="Delivery Method";<br>
oSheet.Cells(row, col+1)="First Choice";<br>
oSheet.Cells(row, col+2)=selectedDeliveryFirstChoice;<br>
oSheet.Cells(row, col+3)="Second Choice";<br>

 if(selectedDeliverySecondChoice != "-Select-")<br>

oSheet.Cells(row, col+4)=selectedDeliverySecondChoice;<br>
row +=2;<br>
//alert(VESSApplications.rows.length);<br>
if(VESSApplications.rows.length>0)<br>
{<br>
 for (var y = 0; y < VESSApplications.rows.length; y++) <br>
 {<br>
     for (var x = 0; x < VESSApplications .rows(y).cells.length; x++) <br>
     {<br>
   //          oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br>
         oSheet.Cells(row, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br>

     }<br>
             row++;<br>

 }<br>
 //   oExcel.Visible = true;<br>
  // oExcel.UserControl = true;<br>
}<br>

else<br>
{<br>
alert("There is no VESS/Other Applications to Export!");<br>
}<br>
row +=2;<br>

//Other Applications<br>

 /*     for (var y = 0; y < OtherApplications.rows.length; y++) <br>
 {<br>
     for (var x = 0; x < OtherApplications.rows(y).cells.length; x++) <br>
     {<br>
         oSheet.Cells(row, x + 1) = OtherApplications.rows(y).cells(x).innerText;<br>

     }<br>
             row++;<br>

 }<br>


   row +=2;<br>


//MFG Applications<br>

 for (var y = 0; y < MFGApplications.rows.length; y++) <br>
 {<br>
     for (var x = 0; x < MFGApplications.rows(y).cells.length; x++) <br>
     {<br>
   //          oSheet.Cells(y + 1, x + 1) = VESSApplications .rows(y).cells(x).innerText;<br>
         oSheet.Cells(row, x + 1) = MFGApplications.rows(y).cells(x).innerText;<br>

     }<br>
             row++;<br>

 }<br>

 */  
oSheet.columns.autofit;<br>


 oExcel.Visible = true;<br>
 oExcel.UserControl = true;<br>
}<br>
else<br>
{<br>
 alert('No VESS/Other applications available to export');<br>
}<br>
}<br>