zoukankan      html  css  js  c++  java
  • 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日

  • 相关阅读:
    删除表中存在多条相同记录的方法
    .Net与设计模式之笔记一
    再来一个莫名其妙的错误(asp.net)
    水晶报表的5种表格设计模式(转)
    【web标准设计】学习、提高、欣赏网站推荐
    UML 对象模型图阅读指南 (转)
    attachEvent传递给其handler的一个默认参数
    ASP.NET2.0 在head中添加了代码块后出现的问题
    js技巧转义符"\"的妙用(转)
    VSS新建项目后导致项目组成员不能打开解决方案的解决方法
  • 原文地址:https://www.cnblogs.com/YFYQ/p/13228455.html
Copyright © 2011-2022 走看看