首頁 >php教程 >PHP源码 >php 导出数据到excel类

php 导出数据到excel类

PHP中文网
PHP中文网原創
2016-05-25 17:12:431174瀏覽

将数据导出到excel当中

<?php
/**
 * 导出到excel文件(一般导出中文的都会乱码,需要进行编码转换)
 * 使用方法如下
 * $excel = new Excel();
 * $excel->addHeader(array(&#39;列1&#39;,&#39;列2&#39;,&#39;列3&#39;,&#39;列4&#39;));
 * $excel->addBody(
            array(
                array(&#39;数据1&#39;,&#39;数据2&#39;,&#39;数据3&#39;,&#39;数据4&#39;),
                array(&#39;数据1&#39;,&#39;数据2&#39;,&#39;数据3&#39;,&#39;数据4&#39;),
                array(&#39;数据1&#39;,&#39;数据2&#39;,&#39;数据3&#39;,&#39;数据4&#39;),
                array(&#39;数据1&#39;,&#39;数据2&#39;,&#39;数据3&#39;,&#39;数据4&#39;)
            )
        );
 * $excel->downLoad();
 */
class Excel{
    private $head;
    private $body;
     
    /**
     * 
     * @param type $arr 一维数组
     */
    public function addHeader($arr){
        foreach($arr as $headVal){
            $headVal = $this->charset($headVal);
            $this->head .= "{$headVal}\t ";
        }
        $this->head .= "\n";
    }
     
    /**
     * 
     * @param type $arr 二维数组
     */
    public function addBody($arr){
        foreach($arr as $arrBody){
            foreach($arrBody as $bodyVal){
                $bodyVal = $this->charset($bodyVal);
                // 过滤特殊字符
                $bodyVal = str_replace(array(&#39;\\n&#39;,&#39;\\t&#39;,&#39;<br>&#39;,&#39;<br />&#39;, &#39;<br>&#39;,&#39;</br>&#39;), "", $bodyVal);
                $bodyVal = str_replace(array("rn", "r", "n"), "", $bodyVal);
                $bodyVal =preg_replace("{\t}","",$bodyVal);
                $bodyVal=preg_replace("{\r\n}","",$bodyVal);
                $bodyVal=preg_replace("{\r}","",$bodyVal);
                $bodyVal=preg_replace("{\n}","",$bodyVal);
                $bodyVal = str_replace(",", " ",$bodyVal);
                $this->body .= "{$bodyVal}\t ";
            }
            $this->body .= "\n";
        }
    }
     
    /**
     * 下载excel文件
     */
    public function downLoad($filename=&#39;&#39;){
        if(!$filename)
            $filename = date(&#39;YmdHis&#39;,time()).&#39;.xls&#39;;
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=$filename"); 
        header("Content-Type:charset=gb2312");
        if($this->head)
            echo $this->head;
        echo $this->body;
    }
     
    /**
     * 编码转换
     * @param type $string
     * @return string
     */
    public function charset($string){
        return iconv("utf-8", "gb2312", $string);
    }
}
?>


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn