PHP代码 - 简单、实用、美好的导出代码

卷首语:

       作为后端攻城狮,在后台系统中,我们经常会遇到导出操作,常规情况,我们是找PHPExcel类来实现这个功能,但是,今天不用了,因为我在【PHP中文网】看到了一个超级好用的导出实现,所以,忍不住【转载加修改】的方式,贴出来,方便自己,也希望能方便到其他人。“All for one , one for all”, 愿程序世界更美好!

一、后台页面

  1. Html代码:
    <form id="searchForm" class="form-inline" role="form" action="/distribute/index/" method="get">
        <div class="form-group padding-5">
            <label class="control-label">订单id:</label>
            <input style="width:80px;" type="text" class="form-control" placeholder="订单id" name="orderid" id="orderid" value="{$param.orderid}">
        </div>
        <div class="form-group padding-5">
            <label class="control-label">是否分账:</label>
            <select name="is_distribute_money">
                <option value="">请选择</option>
                {if $param.is_distribute_money==1}
                <option value="1" selected>已分账</option>
                {else}
                <option value="1">已分账</option>
                {/if}
                {if $param.is_distribute_money==='0'}
                <option value="0" selected>待分账</option>
                {else}
                <option value="0">待分账</option>
                {/if}
            </select>
        </div>
        <input type="hidden" name="is_export" id="is_export" value="0">
        <button type="submit" class="btn btn-blue" style="margin-left: 15px;" id="select">查询</button>
        <button type="submit" class="btn btn-blue" style="margin-left: 15px;" id="export">导出</button>
    </form>

    注:通常,我们的导出和搜索是在一块的,所以,我们在这里做一个简单的隐藏域,作为标记,是否进行导出(1,是;0,否)。

  2.   Javascript代码:
    <script>
        //查询数据
        $("#select").on('click',function(){
            $('#is_export').val(0);
            $('#searchForm').submit();
        });
    
        //导出数据
        $("#export").on('click',function(){
            $('#is_export').val(1);
            $('#searchForm').submit();
        });
    <script>

    注:当我们提交form表单的时候,对是否导出(is_export)进行标记,后台,通过判断is_export是否为1,进行导出或查询操作,这么做的目的是,根据条件查询的结果导出,比较友好!

二、核心代码

    /**
     * @param array $data 要导出的数据
     * @param array $title excel表格的表头
     * @param string $filename 文件名
     */
    public function daochu_excel($data=array(),$title=array(),$filename='报表'){//导出excel表格
        //处理中文文件名
        ob_end_clean();
        Header('content-Type:application/vnd.ms-excel;charset=utf-8');
        
        header("Content-Disposition:attachment;filename=export_data.xls");
        //处理中文文件名
        $ua = $_SERVER["HTTP_USER_AGENT"];
        
        $encoded_filename = urlencode($filename);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        if (preg_match("/MSIE/", $ua) || preg_match("/LCTE/", $ua) || $ua == 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko') {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
        }else {
            header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
        }
        header ( "Content-type:application/vnd.ms-excel" );
        
        
        $html = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
            <html xmlns='http://www.w3.org/1999/xhtml'>
            <meta http-equiv='Content-type' content='text/html;charset=UTF-8' />
            <head>
     
            <title>".$filename."</title>
            <style>
            td{
                text-align:center;
                font-size:13px;
                font-family:Arial, Helvetica, sans-serif;
                font-family:SimHei;
                /*border:#1C7A80 1px solid;*/
                border:gainsboro 1px solid;
                color:#152122;
                width:auto;
            }
            table,tr{
                border-style:none;
            }
            .title{
                /*background:#7DDCF0;*/
                background: green;
                color:#FFFFFF;
                font-weight:bold;
            }
            </style>
            </head>
            <body>
            <table width='100%' border='1'>
              <tr>";
        foreach($title as $k=>$v){
            $html .= " <td class='title' style='text-align:center; height:80px; font-size: 15px;'>".$v."</td>";
        }
        
        $html .= "</tr>";
        
        foreach ($data as $key => $value) {
            $html .= "<tr>";
            foreach($value as $aa){
                $html .= "<td>".$aa."</td>";
            }
            
            $html .= "</tr>";
            
        }
        $html .= "</table></body></html>";
        echo $html;
        exit;
    }

三、调用代码

if($get['is_export'] && $order_list['list']){
            //echo count($order_list['list']),$order_list['count'];exit();
            $export_data = [];
            foreach ($order_list['list'] as $key=>$val) {
                $export_data[$key]['orderid'] = $val['orderid'];
                $export_data[$key]['coach_name'] = $val['coach_name'];
                $export_data[$key]['gym_name'] = $val['gym_name'];
                $export_data[$key]['course_name'] = $val['course_name'];
                $export_data[$key]['user_name'] = $val['user_name'];
                $export_data[$key]['price'] = $val['price'];
                $export_data[$key]['gym_fee'] = $val['gym_fee'];
                $export_data[$key]['coach_fee'] = $val['coach_fee'].($val['is_active']==1?'<font color="red">(教练半价优惠)</font>':'');
                $export_data[$key]['plat_fee'] = $val['plat_fee'];
                $export_data[$key]['status_desc'] = $val['status_desc'];
                $export_data[$key]['createtime'] = $val['createtime'];
                $export_data[$key]['account_status_desc'] = "<font color='".($val['account_status_desc']=='待分账'?'red':'green')."' >".$val['account_status_desc']."</font>";
            }
            $title = ['订单id', '教练名称', '健身房名称', '课程名称', '用户名称', '付款金额', '健身房分账', '教练分账', '喔帮分账', '订单状态', '创建时间', '是否分账'];
            $fileName = '私教订单导出数据-'.date('YmdHis',time());
            $this->order_service->daochu_excel($export_data, $title, $fileName);
}

注意:这个方法最好用的,就是参数简洁、明了,一看就懂,【标头,数据,文件名】,几个标头,几个字段的数据,好用!另外,分页这里得判断一下,当如果导出的时候,可以将这个数设置的大一点,或者,你也可以设为查询的总数。

$page = $params['per_page'] ? $params['per_page'] : self::PAGE;
$pagesize = $params['pagesize'] ? $params['pagesize'] : self::PAGESIZE;
if($params['is_export']){
     $pagesize = 100000; // 导出用
}

四、导出结果

写在最后:

       做程序好几年了,直到最近才如饥似渴地往自己的CSDN发文,感觉有点晚,但想想,只要坚持,努力上进,还是有希望做一个优秀的【攻城狮】的!最后,替【PHP中文网】打个广告,PHPstudy,是【PHP中文网】的,之前还真没注意,他们的免费精神,很赞!

发布了59 篇原创文章 · 获赞 2 · 访问量 5594

猜你喜欢

转载自blog.csdn.net/LDR1109/article/details/99310212