PHP excel导出功能

就是取出需要的数据,然后写入excel文件里
先取出数据

//excel导出
    public function export_excel(){
        $xlsCell  = array('手机号','注册时间','昵称','姓名','性别','学习编号','身份证号','民族','籍贯','政治面貌','婚否','户口所在地','邮箱','通信地址','工作单位','学历','年级','在读院校','紧急联系人姓名','紧急联系人电话','班主任');
        $getid = $_POST['id'];
        $startime = $_POST['start_time'].' 00:00:00';
        $endtime = $_POST['end_time'].' 23:59:59';
        if(!$getid){
            $where = "1=1";
            if($startime){
                $where .= " and create_time >= '$startime'";
            }
            if($endtime){
                $where .= " and create_time <= '$endtime'";
            }
            $user = M('users')->field('id,mobile,create_time,user_nicename')->where($where)->order("create_time asc")->select();
            foreach($user as $v){
                $userid = $v['id'];
                $usershow = M('user_show')->field('id,uid',true)->where("uid = '$userid'")->find();
                unset($v['id']);
                $newuser = array_merge($v, $usershow); 
                $data[] = $newuser;
            }
        }else{
            foreach($_POST['id'] as $v){
                $user = M('users')->field('mobile,create_time,user_nicename')->where("id = '$v'")->find();
                $usershow = M('user_show')->field('id,uid',true)->where("uid = '$v'")->find();
                $usershow['sex'] == 1?$usershow['sex']='男':$usershow['sex']='女';
                $newuser = array_merge($user, $usershow); 
                $data[] = $newuser;
            }
        }
        getexcel($data,$xlsCell,'test');die;
    }

接下来是写入excel的 getexcel方法 将取出的数组数据,放到table表格里写入excel就好了 table还可以添加style样式

/*
 * $data 要写入的数据   数组
 * $title 表头
 * $filename    导出的文件名字
 * */
function getexcel($data=array(),$title=array(),$filename='report'){
    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Content-type:application/vnd.ms-excel;charset=utf-8");  
    header("Content-Disposition:attachment;filename=".$filename.".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    ob_clean();
    //导出xls 开始
    echo "";
   
    if (!empty($title)){
        foreach ($title as $k => $v) {
//              $title[$k]=iconv("UTF-8", "GB2312",$v);
            $titltstr .= "$v";
        }
        echo "$titltstr"; 
    }
    if (!empty($data)){
        foreach($data as $k => $v){
            foreach($v as $key => $vv){
                $arr[$k][] = $vv;
            }
        }
        foreach($arr as $v){
            echo "";
            foreach($v as $vv){
//                  $vv = iconv("UTF-8", "GB2312",$vv);
                echo  "";
            }
            echo "";
        }
        echo "
$vv
"; } }

你可能感兴趣的:(PHP excel导出功能)