简体   繁体   中英

export jqgrid data to xsl/excel using zend framework

im trying to export a jqgrida data to excel or csv file, and i was following this example php + jqgrid + export to excel , but after i click the button to export the data nothing happens. here goes the code..

this is my list.phtml where i render the grid, and once i press the button export do excel,it fecthes the data from jqgrid and send it to the action /checkins/export.

<div class="simplebox grid740" style="z-index: 500;">


    <script>
        $(function() {
            $("#toolbar").jqGrid({ 
                caption:"Checkins",
                colNames:['ID','Nome da Tag','Localização da Tag','Cliente','Utilizador','Data da Leitura','Data da Escrita',],
                colModel:[

                    {name:'id_checkin',index:'id_checkin',hidden:true},
                    {name:'tag_nome',index:'tag_nome'},
                      {name:'localizacao',index:'localizacao'},
                        {name:'nome_cli',index:'nome_cli'},
                          {name:'nome_user',index:'nome_user'},
                            {name:'data_leitura',index:'data_leitura'},
                              {name:'data_escrita',index:'data_escrita'},



                ],
                datatype:"json",
                height:421, 
                rownumWidth:40,
                pager:'#ptoolbar',
                rowList:[10,20,30],
                rowNum:10,
                sortname:'id_cliente',
                sortorder:'desc',
                url:'/checkins/list/',
                viewrecords:true,
                width:740,


            });
            $("#toolbar").jqGrid('navGrid','#ptoolbar',{del:false,add:false,edit:false,search:false,excel:true});
            jQuery("#toolbar").jqGrid('navButtonAdd','#ptoolbar',{
            caption:"export", 
            onClickButton : function () { 
            alert('export to excel');
            var mya=new Array();
        mya=$("#toolbar").getDataIDs();  // Get All IDs
        var data=$("#toolbar").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=$("#toolbar").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
         $.ajax({
                            url: '/checkins/export',
                            type: 'POST',
                            data: {param1: html},
                            datatype: "json"


                    });

       } 
});
        });
    </script>

    <table id="toolbar"></table>
    <div id="ptoolbar"></div>

</div>

so according to firebug the it send this: param1:

id_checkin tag_nome localizacao nome_cli nome_user data_leitura data_escrita

1 sasa Maia;Porto; tesret1212; admin 2013-08-14 15:45:00 2013-08-14 16:00:00

2 sasa Maia;Porto; tesret1212; tre 2013-08-14 16:06:00 2013-08-14 16:05:00

3 sasa Maia;Porto; tesret1212; teste 2013-08-14 12:15:00 2013-08-14 16:15:00

and in my action /checkins/export im doing this:

   public function exportAction()
    {
         if($this->_request->isXmlHttpRequest())
        {

            $this->_helper->layout()->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
            $param1 = $this->_request->getParam('param1');
             header("Content-Type: application/vnd.ms-excel");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("content-disposition: attachment;filename=contacts-download-" . time() . ".xls");

            $buffer = $param1;

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

            }
        }
    }

in here a im receiving the param1 info and setting the headers and then echo the data. But the box asking to download the file isnt appearing, i have tried other solution, but nothing works...what am i missing. it is possible to render the view as a csv/excel file, by set creating a excel layout? thanks in advance Hugo

I was implementing same things as below and it work fine Below is my jqgrid code

jQuery("#list2").jqGrid('navButtonAdd', '#pager2', {
      caption: "Download", buttonicon:"ui-icon-save", title: "Excel Export",
      onClickButton: function(){ 
          exportExcel();
        }, 
        position:"last"
                      });
      }
       function exportExcel()
       {
  var mya=new Array();
  mya=$("#list2").getDataIDs();  // Get All IDs
  var data=$("#list2").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=$("#list2").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
  console.log(html);
   document.forms[0].csvBuffer.value=html;
   document.forms[0].method='POST';
   document.forms[0].action='analytics.do?method=getDownload';
   document.forms[0].target='_blank';
   document.forms[0].submit();
 } 

add below three lines in your html code

<form id='_export' method="post" action="">
<input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
</form>

and your server code for downloading csv file as

 public void getDownload(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception{
    PrintWriter out = response.getWriter();
         String param1 = request.getParameter("csvBuffer");
         response.setContentType("application/octet-stream");
         response.setHeader("Content-Disposition",
         "attachment;filename=downloadfilename.csv");
        try{
            System.out.println(param1);
            out.print(param1);
        }catch(Exception $e){

        }

} //end of getDownload method

So it download file as csv format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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