php + jqgrid + export to excel
Asked Answered
C

6

20

Somebody knows a way to export the data from a jqgrid to excel?

I want to do a report using this jqgrid that i think is awsome. But i need to save or print this report somehow, because is information to be keeped. Somebody knows any way??

Cychosz answered 3/2, 2010 at 0:11 Comment(0)
A
12

This is my approach, just add this code to your js/html file

$("#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

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){

}
Auriculate answered 26/8, 2010 at 9:33 Comment(3)
Thanks for share your code Felix Guerrero. I have a problem: when I run your code I get this error: document.forms[0].csvBuffer is undefined, can you help me to fix this?Precipitous
This code does appear to consider only visible rows, have you any hint on how to get the full list (i.e. not only the rows in current page)?Mitchel
Thanks Felix ,i used this example with jspdf and it was very usefull, thaks a lot.Wellnigh
M
3

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.

<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?

thank you ~

Mirilla answered 18/11, 2010 at 7:57 Comment(0)
D
3

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)

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 ;. Then an anchor tag is created with certain attributes. Finally click is called on a to download the file.

You could have a look at several excel MIME Types : MIME Type List

Dynast answered 16/11, 2015 at 10:46 Comment(0)
X
2

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));
    }
  });
}
Xerosis answered 25/6, 2011 at 16:22 Comment(0)
G
1

I solved your problem .and now iam able to export data excel with column names please refer my code.

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.

Gualterio answered 19/1, 2011 at 7:39 Comment(0)
H
0

create a form and a hidden element with the name "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.

Hotheaded answered 3/11, 2010 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.