web页面中导出Excel (方法三) 前端easyui-datagrid(分页)导出Excel 使用 datagrid-export.js

发布时间 2023-06-14 14:43:03作者: 海乐学习

这个示例使用  前端 easyui-datagrid  后端 php 

前端 easyui-datagrid 导出Excel 使用了 datagrid-export.js 

datagrid-export.js 文件可自行搜索下载

优点:查询结果显示在datagrid中(可以分页),前端直接下载不用回后端,效率高速度快。

缺点:页面中有两个  easyui-datagrid 组件,一个用于显示(分页),一个用于导出(不分页)。

          自认为此方法较好,不足之处就是数据量不能太大,几万行或检索速度慢,会发生http超时。若数据量巨大,在网页上做导出Excel就不太适合了。

界面

页面上有两个gird,其中 grid_toexcel 是要隐藏的

操作原理:虽然两个gird的数据都请求至一个php中但通过 $_GET['target'] 参数来判断

                 grid 带分页   用于显示   查询按钮操作

                 grid_toexcel 不带分页,检索全部,用于导出   导出按钮操作

html

    <div style='padding:0px 0px 15px 12px ;'> 
        <table> 
            <tr> 
                <td style="width:65px;">开始时间:</td> 
                <td style="padding: 0px 0px 0px 2px;"> <input id="start_date_entered" value="<{$start_date}>" placeholder="开始日期" class="my_input laydate-icon" style="height:29px;"  onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})" readonly ></input></td> 
                <td><span class="my_span" ></span></td>  
                <td><input id="stop_date_entered" value="<{$stop_date}>" placeholder="结束日期" class="my_input laydate-icon" style="height:29px;" onclick="laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})"  readonly  ></input>    </td> 
                <td style="width:10px;"> </td>
                <td class='width:75px;'>坐席员:&nbsp;</td> 
                <td><select id="select_agent_name" name="select_agent_name" class="easyui-combobox" style="height:28px;width:160px;" editable=false  ><{$select_option_agent_name}></select></td> 
                <td style="width:10px;"> </td>
                <td style="padding: 0px 0px 0px 5px;"> 
                    <a href='#' class='easyui-linkbutton'   iconCls='icon-select' style="height:29px;width:64px;" onclick='Select()'>查询</a> 
                </td>
            </tr>
        </table> 
    </div>  
    <table id='grid'class='easyui-datagrid' style='width:1250px;min-height:450px'  
            title='列表' iconCls='icon-table' pagination='true' rownumbers='true' fitColumns='true' singleSelect='true' toolbar='#toolbar' >   
            <!-- rownumbers='true' fitColumns='true' singleSelect='true' toolbar='#toolbar'  remoteSort='false'>   不分页 -->
        <thead>  
            <tr>  
                <!-- <th field='select' width='30' align='center'></th>   
                <th field='id' width='10' hidden='true'>编号</th>       --> 
                <th field='agent_name' width='25'align='center' sortable='true' >坐席工号</th> 
                <th field='user_name' width='25'align='center' sortable='true' >坐席员</th> 
                <th field='start_time' width='40'align='center' sortable='true' >开始时间</th>
                <th field='stop_time' width='40'align='center' sortable='true' >结束时间</th> 
                <th field='time_len' width='20'align='center' sortable='true' >时长</th> 
                <th field='time_len_s' width='20'align='center' sortable='true' >时长(秒)</th> 
                <th field='status' width='20'align='center' sortable='true' >状态</th>  
                <th field='description' width='80'align='center' sortable='true' >描述</th> 
            </tr>  
        </thead>  
    </table>  
    <div id='div_toexcel' class='easyui-panel' closed='true'><!-- 用于导出 -->
        <table id='grid_toexcel' class='easyui-datagrid'> 
        </table>  
    </div>

    <div id='toolbar' style='display: flex;align-items:Center; height:35px;' > 
        <a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-excel' plain='true' onclick='ToExcel()' <{$ToExcel_disabled}> >导出</a> 
        <div class="btn-separator"></div>
        <a href='#' class='easyui-linkbutton' iconCls='icon-refresh' plain='true' onclick='Refresh()'>刷新</a> 
        <a href='#' class='easyui-linkbutton'  iconCls='icon-cancel' plain='true' onclick='parent.TabClose();'>关闭</a>   
    </div> 

js

&target=ToExcel 这个GET值是用于 区别是点查询还是点导出按钮的。目的就是一个分页检索,一个不分页检索

<script type="text/javascript" src="themes/easyui/datagrid-export.js"></script> <!-- datagrid-export.js 方式 -->
<body>   
function Select(){   
        var agent_name=$('#select_agent_name').combobox('getValue');
        var start_time=$('#start_date_entered').val();   
        var stop_time=$('#stop_date_entered').val();
         
        var url='Api-index.php?module=<{$module_name}>&action=Api_ReportView_Agent_FreeBusy_List_Select<{$get_current_user}>' ;  
        var query={'agent_name':agent_name,'start_time':start_time,'stop_time':stop_time   };
        $('#grid').datagrid('options').url=url;   
        $('#grid').datagrid('options').queryParams=query;   
        $('#grid').datagrid('reload');      
}  
    
function ToExcel(){
        //$('div_toexcel').panel('close');//grid_toexcel 显示、隐藏
        //$('div_toexcel').panel('open');

        //将grid的表结构(列名)赋给grid_toexcel
        var cols=$('#grid').datagrid('options').columns;
        //console.log(cols[0]);
        $('#grid_toexcel').datagrid({columns:[cols[0]]}).datagrid("reload");

        var agent_name=$('#select_agent_name').combobox('getValue');
        var start_time=$('#start_date_entered').val();   
        var stop_time=$('#stop_date_entered').val();
         
        var url='Api-index.php?module=<{$module_name}>&action=Api_ReportView_Agent_FreeBusy_List_Select&target=ToExcel<{$get_current_user}>' ;  
        var query={'agent_name':agent_name,'start_time':start_time,'stop_time':stop_time   };
        //alert(query);

        //请求数据------------------------------
        $.ajax({
            type: "POST",
            url: url, //后台php文件的地址
            data: query, //查询参数
            dataType: "json",
            success:function (data) {
                //alert("提交成功"+JSON.stringify(data));
             //console.log('data.length '+data.rows.length); 

                $("#grid_toexcel").datagrid("loadData", data.rows);  //动态取数据

                $('#grid_toexcel').datagrid('toExcel','Book.xls'); //datagrid-export.js 方式  导出Excel
            },
            error:function (data) {
                alert("导出失败 "+JSON.stringify(data));
            }
        }); 
     //-------------------------------------------------
    }

</script>  

php

<?php 
/*          
foreach($_POST as $k=>$v){    
    WriteLog("POST " . $k .'--' .$v);    
}    
foreach($_GET as $k=>$v){    
    WriteLog("GET " .  $k .'--' .$v);    
}    
*/   
//---------------------------------------------查询列表------------------------------------
    $arr_result = array(); //返回值  
    $where='';//查询条件  
    if(!empty($_POST['start_time'])){
        $start_time=$_POST['start_time'];    
        $stop_time=$_POST['stop_time'];    
    }
    else{
        //当天
        $start_time=date("Y-m-d 0:0:0",strtotime("now"));
        $stop_time=date("Y-m-d 23:59:59",strtotime("now"));    
    }    
    $where=" start_time >='{$start_time}' and start_time <='{$stop_time}' ";  
    
    //坐席
    if($_REQUEST['agent_name']!='' && $_REQUEST['agent_name']!='0'){  // 
        $where .=" and agent_name = '{$_REQUEST['agent_name']}' ";  
    } 
 
    //结果集      
    $items = array(); 
    //整合条件
    $where= " " . $where;
    $order_by=" ORDER BY start_time asc"; //条件
    $limit=" limit $offset,$rows ";//分页

    //导出 或 打印  不分页
    if($_GET['target']=="ToExcel"){ //  || $_GET['target']=="Print" 
        $limit="  ";//分页为空
    }else{
        //分页
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;   
        $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;   
        $offset = ($page-1)* $rows;   
        
        $sql ="SELECT COUNT(cti_agent_free_busy.id) AS total FROM cti_agent_free_busy join user on cti_agent_free_busy.agent_name=user.user_id where  " . $where ;   
        //WriteLog($sql);  
        $arr_result['total'] =$db->query_count($sql);//查询 总条数
        
        $limit="   limit $offset,$rows ";//分页
    }
    
    $sql="SELECT c.agent_name , u.user_name as user_name,c.date,c.start_time,c.stop_time,c.time_len,c.time_len_s,c.status,c.description  FROM ";
    $sql.=" cti_agent_free_busy as c  join user as u on c.agent_name=u.user_id where ";
    $sql.=" " .$where .$order_by  .$limit;   
    //WriteLog($sql);  

    $result_rows=$db->query($sql); 
    $row_count=$db->num_rows($result_rows);//行数

    while($row=$db->fetch_array($result_rows))  
    {         
        array_push($items, $row);          
    }
 
    $arr_result['rows'] = $items;       


    echo json_encode($arr_result);   

?>