dongtui6347 2013-08-14 18:00
浏览 45

使用zend框架将jqgrid数据导出到xsl / excel

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+"
";                    // 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+"
";  // output each row with end of line

            }
        html=html+"
";  // 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

  • 写回答

1条回答 默认 最新

  • douou1891 2013-10-08 07:01
    关注

    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+"
    ";                    // 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+"
    ";  // output each row with end of line
    
          }
      html=html+"
    ";  // 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.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)