php 导出数据到excel类

原文链接地址:http://www.oschina.net/code/snippet_212240_21885

标注:在使用时一定要屏蔽掉//$bodyVal = $this->charset($bodyVal);,不然传到里面的中文变量输不出来,这个应该是转换编码格式的。

  1 <?php
  2 
  3 /**
  4 
  5  * 导出到excel文件(一般导出中文的都会乱码,需要进行编码转换)
  6 
  7  * 使用方法如下
  8 
  9  * $excel = new Excel();
 10 
 11  * $excel->addHeader(array('列1','列2','列3','列4'));
 12 
 13  * $excel->addBody(
 14 
 15             array(
 16 
 17                 array('数据1','数据2','数据3','数据4'),
 18 
 19                 array('数据1','数据2','数据3','数据4'),
 20 
 21                 array('数据1','数据2','数据3','数据4'),
 22 
 23                 array('数据1','数据2','数据3','数据4')
 24 
 25             )
 26 
 27         );
 28 
 29  * $excel->downLoad();
 30 
 31  */
 32 
 33 class Excel{
 34 
 35     private $head;
 36 
 37     private $body;
 38 
 39     
 40 
 41     /**
 42 
 43      * 
 44 
 45      * @param type $arr 一维数组
 46 
 47      */
 48 
 49     public function addHeader($arr){
 50 
 51         foreach($arr as $headVal){
 52 
 53             $headVal = $this->charset($headVal);
 54 
 55             $this->head .= "{$headVal}\t ";
 56 
 57         }
 58 
 59         $this->head .= "\n";
 60 
 61     }
 62 
 63     
 64 
 65     /**
 66 
 67      * 
 68 
 69      * @param type $arr 二维数组
 70 
 71      */
 72 
 73     public function addBody($arr){
 74 
 75         foreach($arr as $arrBody){
 76 
 77             foreach($arrBody as $bodyVal){
 78 
 79                 //$bodyVal = $this->charset($bodyVal);
 80 
 81                 $this->body .= "{$bodyVal}\t ";
 82 
 83             }
 84 
 85             $this->body .= "\n";
 86 
 87         }
 88 
 89     }
 90 
 91     
 92 
 93     /**
 94 
 95      * 下载excel文件
 96 
 97      */
 98 
 99     public function downLoad($filename=''){
100 
101         if(!$filename)
102 
103             $filename = date('YmdHis',time()).'.xls';
104 
105         header("Content-type:application/vnd.ms-excel");
106 
107         header("Content-Disposition:attachment;filename=$filename"); 
108 
109         header("Content-Type:charset=gb2312");
110 
111         if($this->head)
112 
113             echo $this->head;
114 
115         echo $this->body;
116 
117     }
118 
119     
120 
121     /**
122 
123      * 编码转换
124 
125      * @param type $string
126 
127      * @return string
128 
129      */
130 
131     public function charset($string){
132 
133         return iconv("utf-8", "gb2312", $string);
134 
135     }
136 
137 }
138 
139 ?>

 

posted @ 2015-05-20 14:30  yense  阅读(206)  评论(0编辑  收藏  举报