2010-02-03 26 views
19

¿Alguien sabe cómo exportar los datos de un jqgrid a Excel?php + jqgrid + exportar a excel

Quiero hacer un informe usando esta jqgrid que creo que es impresionante. Pero necesito guardar o imprimir este informe de alguna manera, porque es información que debe guardarse. ¿Alguien sabe de alguna manera?

Respuesta

11

Este es mi enfoque, sólo tiene que añadir este código a su archivo 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(); 
     } 

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

} 
+1

Gracias por su código de cuota de Félix Guerrero. Tengo un problema: cuando ejecuto el código obtengo este error: document.forms [0] .csvBuffer no está definido, ¿me pueden ayudar a solucionarlo? –

+0

Este código parece tener en cuenta solo las filas visibles, ¿tiene alguna pista sobre cómo obtener la lista completa (es decir, no solo las filas en la página actual)? – Don

+0

¿Esto capta datos del back-end? Supongo que no.. –

0

crear una forma y un elemento oculto con el nombre "csvBuffer". Este elemento se establece por la función. que tenía que cambiar la línea

html = html+"\n" 

a

html = html+"\\n" 

con el fin de escapar de ella adecuadamente.

3

muy buena pregunta, me estaba rascando la cabeza sobre esto también. Lo hice eligiendo la sugerencia de Felix, permítanme completarlo agregando las siguientes líneas a su cuerpo html.

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

El único problema que tengo es el archivo de Excel exportado duerma incluye mis nombres de columna en jqGrid, también hay una manera de excluir a determinadas columnas o varias al exportar a archivo de Excel?

gracias ~

1

He resuelto el problema .y ahora iam capaz de exportar datos de Excel con los nombres de las columnas consulte mi código.

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

Háganme saber si encuentra algún problema.

2

¡Gran función!
He realizado cambios.

 
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)); 
    } 
    }); 
} 
1

Aquí es una solución inteligente para guardar los datos jqGrid como hoja de Excel sin llamar a la secuencia de comandos php: (Sólo necesita llamar a esta función con GridID y un opcional 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(); 
} 

en primer lugar, crear una cadena delimitada con CSV;. Entonces se crea una etiqueta anchor con ciertos atributos. Finalmente, se llama al click en a para descargar el archivo.

Se puede echar un vistazo a varios tipos MIME de Excel: MIME Type List