• 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;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"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns="http://www.w3.org/TR/REC-html40">
    <head>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    </head>
    <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>
    "; 
        } 
        $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日

  • 相关阅读:
    js 匿名函数的链式调用
    mysql 数据库操作的一般操作命令
    js 截取一定数量的字节
    js 截取10个字节
    BootStrap入门教程 (四)
    安装Dedecms遇到的一系列问题
    BootStrap入门教程 (三)
    dedecms标签调用大全
    artDialog皮肤引入方式
    织梦cms安装完成后登录后台出现空白。主要原因是php版本的问题
  • 原文地址:https://www.cnblogs.com/YFYQ/p/13228455.html
Copyright © 2020-2023  润新知