简体   繁体   English

php + jqgrid +导出到excel

[英]php + jqgrid + export to excel

Somebody knows a way to export the data from a jqgrid to excel? 有人知道将数据从jqgrid导出到excel的方法吗?

I want to do a report using this jqgrid that i think is awsome. 我想用这个jqgrid做一个我认为很棒的报告。 But i need to save or print this report somehow, because is information to be keeped. 但我需要以某种方式保存或打印此报告,因为需要保留信息。 Somebody knows any way?? 有人知道吗?

This is my approach, just add this code to your js/html file 这是我的方法,只需将此代码添加到您的js / html文件中

$("#list").jqGrid('navGrid', '#pager',{view:true, del:false, add:false, edit:false, excel:true})
                .navButtonAdd('#pager',{
                                caption:"Export to Excel", 
                                buttonicon:"ui-icon-save", 
                                onClickButton: function(){ 
                                  exportExcel();
                                }, 
                                position:"last"
                            });

        function exportExcel()
        {
            var mya=new Array();
            mya=$("#list").getDataIDs();  // Get All IDs
            var data=$("#list").getRowData(mya[0]);     // Get First row to get the labels
            var colNames=new Array(); 
            var ii=0;
            for (var i in data){colNames[ii++]=i;}    // capture col names
            var html="";
            for(i=0;i<mya.length;i++)
                {
                data=$("#list").getRowData(mya[i]); // get each row
                for(j=0;j<colNames.length;j++)
                    {
                    html=html+data[colNames[j]]+"\t"; // output each column as tab delimited
                    }
                html=html+"\n";  // output each row with end of line

                }
            html=html+"\n";  // end of line at the end
            document.forms[0].csvBuffer.value=html;
            document.forms[0].method='POST';
            document.forms[0].action='csvExport.php';  // send it to server which will open this contents in excel file
            document.forms[0].target='_blank';
            document.forms[0].submit();
        }

PHP script PHP脚本

header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=file.xls");
header("Pragma: no-cache");

$buffer = $_POST['csvBuffer'];

try{
    echo $buffer;
}catch(Exception $e){

}

very good question, i was scratching my head off about this as well. 非常好的问题,我也对此感到头疼。 I made it by choosing Felix's suggestion, let me complete it by adding following lines to your html body. 我通过选择Felix的建议来做到这一点,让我通过在你的html主体中添加以下行来完成它。

<form method="post" action="csvExport.php">
    <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
</form>

The only problem i have is the excel file exported doesnt include my column names in jqgrid, also is there a way to exclude a particular or several columns when exporting to excel file? 我唯一的问题是导出的excel文件不包括我在jqgrid中的列名,还有一种方法可以在导出到excel文件时排除特定或多个列吗?

thank you ~ 谢谢〜

Great function! 功能很棒!
I have made changes. 我做了改变。

function exportExcel($id){
  var keys=[], ii=0, rows="";
  var ids=$id.getDataIDs();  // Get All IDs
  var row=$id.getRowData(ids[0]);     // Get First row to get the labels
  for (var k in row) {
    keys[ii++]=k;    // capture col names
    rows=rows+k+"\t";     // output each Column as tab delimited
  }
  rows=rows+"\n";   // Output header with end of line
  for(i=0;i<ids.length;i++) {
    row=$id.getRowData(ids[i]); // get each row
    for(j=0;j<keys.length;j++) rows=rows+row[keys[j]]+"\t"; // output each Row as tab delimited
    rows=rows+"\n";  // output each row with end of line
  }
  rows=rows+"\n";  // end of line at the end
  var form = "<form name='csvexportform' action='"+php_path+"csvexport.php' method='post'>";
  form = form + "<input type='hidden' name='csvBuffer' value='"+rows+"'>";
  form = form + "</form><script>document.csvexportform.submit();</sc"+"ript>";
  OpenWindow=window.open('', '');
  OpenWindow.document.write(form);
  OpenWindow.document.close();
}

function gridcsvexport(id) {
  $('#'+id).jqGrid('navButtonAdd','#'+id+'_pager',{
    caption:'',
    title:'export',
    buttonicon:'ui-icon-newwin',
    position:'last',
    onClickButton:function (){
      exportExcel($(this));
    }
  });
}

Here is a clever solution to save the jqGrid data as excel sheet without calling the php script: (You just need to call this function with GridID and an optional Filename ) 这是一个聪明的解决方案,将jqGrid数据保存为excel表而不调用php脚本:(您只需要使用GridID和可选的Filename调用此函数)

var createExcelFromGrid = function(gridID,filename) {
    var grid = $('#' + gridID);
    var rowIDList = grid.getDataIDs();
    var row = grid.getRowData(rowIDList[0]); 
    var colNames = [];
    var i = 0;
    for(var cName in row) {
        colNames[i++] = cName; // Capture Column Names
    }
    var html = "";
    for(var j=0;j<rowIDList.length;j++) {
        row = grid.getRowData(rowIDList[j]); // Get Each Row
        for(var i = 0 ; i<colNames.length ; i++ ) {
            html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
        }
        html += '\n';
    }
    html += '\n';

    var a         = document.createElement('a');
    a.id = 'ExcelDL';
    a.href        = 'data:application/vnd.ms-excel,' + html;
    a.download    = filename ? filename + ".xls" : 'DataList.xls';
    document.body.appendChild(a);
    a.click(); // Downloads the excel document
    document.getElementById('ExcelDL').remove();
}

We first create a CSV string delimited with ; 我们首先创建一个用以下分隔的CSV字符串; . Then an anchor tag is created with certain attributes. 然后使用某些属性创建anchor标记。 Finally click is called on a to download the file. 最后在a上调用click来下载文件。

You could have a look at several excel MIME Types : MIME Type List 您可以查看几个excel MIME类型: MIME类型列表

I solved your problem .and now iam able to export data excel with column names please refer my code. 我解决了你的问题。现在我可以用列名导出数据excel,请参考我的代码。

function exportExcel()
    {
        var mya=new Array();
        mya=$("#tblnoupdate").getDataIDs();  // Get All IDs
        var data=$("#tblnoupdate").getRowData(mya[0]);     // Get First row to get the labels
        var colNames=new Array(); 
        var ii=0;
        for (var i in data){colNames[ii++]=i;}    // capture col names
        var html="";
            for(k=0;k<colNames.length;k++)
            {
            html=html+colNames[k]+"\t";     // output each Column as tab delimited
            }
            html=html+"\n";                    // Output header with end of line
        for(i=0;i<mya.length;i++)
            {
            data=$("#tblnoupdate").getRowData(mya[i]); // get each row
            for(j=0;j<colNames.length;j++)
                {
             html=html+data[colNames[j]]+"\t"; // output each Row as tab delimited
                }
            html=html+"\n";  // output each row with end of line

            }
        html=html+"\n";  // end of line at the end
        document.forms[0].csvBuffer.value=html;
        document.forms[0].method='POST';
        document.forms[0].action='<?php echo $baseurl;?>csvexport.php';  // send it to server which will open this contents in excel file
        document.forms[0].target='_blank';
        document.forms[0].submit();
    }

Please let me know if you face any problem. 如果您遇到任何问题,请告诉我。

create a form and a hidden element with the name "csvBuffer". 创建一个名为“csvBuffer”的表单和隐藏元素。 This element gets set by the function. 该元素由函数设置。 I had to change the line 我不得不换线

html = html+"\n"

to

html = html+"\\n"

in order to escape it properly. 为了正确逃脱它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM