PHP 导出excel 精简版

导入导出一般都是比较正常的一些操作

但是博主不想每次导入导出都引入类库,感觉超级麻烦,

虽然麻烦,但是还是建议各位大大,多动手哈,毕竟学习为重嘛。

由于博主的不想麻烦,于是乎就找到了一份导出excel 的精简版的。

主要可以用来做一些小数目的小功能的导出。

由于本方法是上一年找到的,最近用才从尘封的代码中扒拉出来,

原文地址已不可知,如果原文地址大大看到还望勿怪哈。

废话不多说,直接上代码:

/**
 * PHP导出excel
 * @return [type] [description]
 */
public function export()
{
    $dataResult = [];      //todo:导出数据(自行设置) 
    $headTitle = "PHP导出excel"; //标题
    $title = "PHP导出excel"; //文件名
    // $headtitle= "<tr style='height:50px;border-style:none;><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='13' >{$headTitle}</th></tr>"; 
    $titlename = "<tr> 
                   <th >订单ID</th> 
                   <th >订单编号</th> 
                   <th >下单人</th> 
                   <th >手机号</th> 
                   <th >下单时间</th> 
               </tr>"; 
       $filename = $title.".xls"; 
    $this->excelData($dataResult,$titlename,$headTitle,$filename); 
}

调用的时候导出数据和 titlename 的字段要一一对应,另外titlename 的字段可以自行添加删改

然后是最核心的公共方法

/* 
*处理Excel导出 
*@param $datas array 设置表格数据 
*@param $titlename string 设置head 
*@param $title string 设置表头 
*/ 
function excelData($datas,$titlename,$title,$filename){ 
    $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>"; 
    $str .="<table border=1><head><center><h2>".$title."</h2></center></head>"; 
    $str .= $titlename; 
    foreach ($datas  as $key=> $rt ) 
    { 
        $str .= "<tr>"; 
        foreach ( $rt as $k => $v ) 
        { 
            $str .= "<td>{$v}</td>"; 
        } 
        $str .= "</tr>\n"; 
    } 
    $str .= "</table></body></html>"; 
    header( "Content-Type: application/vnd.ms-excel; name='excel'" ); 
    header( "Content-type: application/octet-stream" ); 
    header( "Content-Disposition: attachment; filename=".$filename ); 
    header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); 
    header( "Pragma: no-cache" ); 
    header( "Expires: 0" ); 
    exit( $str ); 
} 

 

其实这个原理很简单就是将数据写入至一个xls的文件

与原本的还是有一些些区别。毕竟不是类库导出,有些不足。

不过用于小功能,或者小批量的导出还是非常方便的。

以上就是本篇内容。

 

2020年07月03日

 

posted @ 2020-07-03 09:24  御风琊穹  阅读(318)  评论(0编辑  收藏  举报

春风十里,我喜欢你。可是你喜欢的人不喜欢你,哈哈....
人来人往,莫失莫忘。最终还是选择淡忘于回忆之中...
落日余晖,待你而归。但你终究不是为我而归..
一米阳光,温暖安放;心若向阳,无谓悲伤;轻安喜乐,次第花开 。