web页面中导出Excel (方法一) 后端php导出Excel

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

其中前端是不是 easyui-datagrid 不重要,这个方法主要是使用后端 php 来实现导出Excel

优点:现在的应用中大部分是分页显示的,在前台只显示一部分,但导出Excel是要看全部的。所以此时用前端js导出则不太好实现。

缺点:当查询数据量较大或较慢时,不建议用此方法,毕竟http请求会超时。如果导出超几万行,则用winform开发导出程序比较好。

界面

html

<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' >   
        <thead>  
            <tr>  
                <th field='agent_name' width='25'align='center' sortable='true' >工号</th> 
                <th field='user_name' width='25'align='center' sortable='true' >坐席员</th> 
                <th field='login_time' width='30'align='center' sortable='true' >登陆时间</th>
                <th field='logout_time' width='30'align='center' sortable='true' >登出时间</th>
                <th field='time_len' width='30'align='center' sortable='true' >在线时长</th>  
                <th field='time_len_s' width='30'align='center' sortable='true' >在线时长(秒)</th> 
                <th field='description' width='30'align='center' sortable='true' >描述</th> 
            </tr>  
        </thead>  
</table>  
<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

实现原理:第一次请求是与查询按钮请求的php文件是一个,通过get来判断,目的是为了与查询得到的结果一致,导出调用只需得到条件和排序

function ToExcel(){
        var query=SelectParameter();
        var url='Api-index.php?module=<{$module_name}>&action=Api_ReportView_Agent_Login_List_Select&target=ToExcel<{$get_current_user}>' ;    
        /* 获取 条件 */
        $.ajax({
            url: url,
            type: "post",
            data: query,
            dataType: "json",
            success: function (data) { //alert(data.where); alert(data.total);
                var where=data.where;//将条件 传出
                var order_by=data.order_by;//排序
                //alert(where);      
                if(where==""){
                    //$.messager.alert('消息','导出时的发生异常,请刷新后,再试! ','info');
                    layer.alert('导出时的发生异常,请刷新后,再试!', { title:"消息",icon: 2, skin: 'layui-layer-molv',closeBtn: 0   } );
                    return;
                }
                location.href=encodeURI('modules/<{$module_name}>/ReportView_Agent_Login_List_ToExcel.php?where='+where +"&order_by=" +order_by);
            }
         }); 
    }

    //获取 查询 条件 参数
    function SelectParameter(){
        var agent_name=$('#select_agent_name').combobox('getValue');
        var start_time=$('#start_date_entered').val();   
        var stop_time=$('#stop_date_entered').val();
        var query={'agent_name':agent_name,'start_time':start_time,'stop_time':stop_time   };
        return query;
    }
//查询按钮
function
Select(){ var query=SelectParameter(); var url='Api-index.php?module=<{$module_name}>&action=Api_ReportView_Agent_Login_List_Select'; $('#grid').datagrid('options').url=url; $('#grid').datagrid('options').queryParams=query; $('#grid').datagrid('reload'); }

php

查询页    Api_ReportView_Agent_Login_List_Select.php

<?php 
//-----------------------------------------------查询------------------------------------
    $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=" date_time >='{$start_time}' and date_time <='{$stop_time}' ";  
    $where=" login_time >='{$start_time}' and login_time <='{$stop_time}' ";  
    //坐席
    if($_REQUEST['agent_name']!='' && $_REQUEST['agent_name']!='0'){  // 
        $where .=" and cti_agent_login.agent_name = '{$_REQUEST['agent_name']}' ";  
    } 
    //结果集      
    $items = array(); 

    //整合条件
    $where= " " . $where;
    $order_by=" ORDER BY login_date asc"; //条件

    //导出 或 打印
    if($_GET['target']=="ToExcel" || $_GET['target']=="Print" ){
            $arr_result['where'] = $where;      //将条件 传出
            $arr_result['order_by'] = $order_by;      //将条件 传出
  
            echo json_encode($arr_result); //将条件 传出
            exit(0);
    }

    //分页
    $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_login.id) AS total FROM cti_agent_login join user on cti_agent_login.agent_name=user.user_id where  " . $where ;   
    //WriteLog($sql);  
    $arr_result['total'] =$db->query_count($sql);//查询 总条数

    $sql="SELECT cti_agent_login.agent_name , user.user_name as user_name,login_date,login_time,logout_time,time_len,time_len_s,cti_agent_login.description  FROM ";
    $sql.=" cti_agent_login join user on cti_agent_login.agent_name=user.user_id where ";
    $sql.=" " .$where .$order_by  ."   limit $offset,$rows ";   

    $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);   

?>   

导出Excel页    ReportView_Agent_Login_List_ToExcel.php

实现原理:通过查询页得到的查询条件(当然也可以不这么做,在此页写也可以,这么做的目的是为了和查询保持一致)

                 在此页 整合查询SQL语句,访问数据库,得到结果集,用php嵌套for循环的方式像写文件方式写出Excel。所以当数据量较大时会慢,容易造成http请求超时。

<?php
error_reporting(E_ALL^E_NOTICE);//Notice不显示 ^E_DEPRECATED
set_time_limit(0);//不设 php 超时限制

require_once('../../config.php'); 
require_once('../../Log/LogHelper2.php');
require_once('../../myClass/myDBHelper2.php'); 

$arr_result = array(); //返回值  
$where='';//查询条件  
$order="";

    if(!empty($_GET['where'])){ 
        if($_GET['where']!=""){
            $where=$_GET['where'];
            if(!empty($_GET['order_by'])){//$_GET['order_by'] 存在则赋值 不存在则默认为""
                $order_by=$_GET['order_by'];
            }else{
                $order_by="";
            }
        }else{
            $where=' 1=0 ';//查不到的数据    
        }
    }else{
        $where=' 1=0 ';//查不到的数据    
    }
    $where=stripslashes($where);
    $order_by=stripslashes($order_by);
 
    //$col=" name,date_entered, callerid , other_tel,call_type,contact_province,contact_city ";
    //$col.=" ,contact_office,address,description,created_user_name,contact_source,remark  ";
    //$sql = "select {$col} from {$table_name} where ".$where .$order_by ;//." limit $offset,$rows ";  

    $sql="SELECT cti_agent_login.agent_name , user.user_name as user_name,login_time,logout_time,time_len,time_len_s,cti_agent_login.description  FROM ";
    $sql.=" cti_agent_login join user on cti_agent_login.agent_name=user.user_id where ";
    $sql.=" " .$where .$order_by;
  
    $row = array(); 
    $row[]="坐席工号";
    $row[]="坐席员";
    $row[]="登陆时间";
    $row[]="登出时间";

    $row[]="在线时长";
    $row[]="在线时长(秒)";
    $row[]="描述";

    $items = array(); 
    array_push($items, $row);
    
    $result=$db->query($sql); 
    while($row1=$db->fetch_array($result)){   
        array_push($items, $row1);  
         
        /*
        for ($i = 0; $i < sizeof($row1); $i++) {  
            WriteLog( $row1[$i] . "1" . "<br>"); 
        } */ 
  
        //$str1=$row1[0].$row1[1].$row1[2].$row1[3];
        //WriteLog($str1);
    } 

  //Excel文件名
  $date_now=date("YmdHis",strtotime("now"));
  $filename="Book".$date_now.".xls";
  
  createExcelFile($fileName,$items);
  return;


  //创建Excel
  function createExcelFile($fileName,$excelData){
      header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
      header ("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT"); 
      header ("Cache-Control: no-cache, must-revalidate"); 
      header ("Pragma: no-cache"); 
      header ('Content-type: application/x-msexcel');  
      header ("Content-Disposition: attachment; filename=Book".$date_now.".xls" ); 
      header ("Content-Description: PHP/INTERBASE Generated Data" ); 
      
      xlsBOF(); // Excel 
      
      for ($row = 0; $row < sizeof($excelData); $row++) {  

        for ($col = 0; $col < sizeof($excelData[$row]); $col++) {  
             
            $value=iconv("UTF-8", "GBK//IGNORE", $excelData[$row][$col]);
            xlsWriteLabel($row,$col,$value); 
        }
      }
      xlsEOF(); // Excel  
      exit();    
  }

  /////////////////////////////////////////////////////////////////////
  //   
  function xlsBOF() { 
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); 
    return; 
  } 
  // Excel end of file footer 
  function xlsEOF() { 
    echo pack("ss", 0x0A, 0x00); 
   return; 
  } 
  // Function to write a Number (double) into Row, Col 
  function xlsWriteNumber($Row, $Col, $Value) { 
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0); 
    echo pack("d", $Value); 
    return; 
  } 
  // Function to write a label (text) into Row, Col 
  function xlsWriteLabel($Row, $Col, $Value ) { 
    $L = strlen($Value); 
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L); 
    echo $Value; 
    return; 
  }


?> 

 

posted @ 2023-06-14 11:28  海乐学习  阅读(169)  评论(0编辑  收藏  举报