将数据导出到excel当中,欢迎大家拍砖
- /**
- * Export to excel file (generally exporting Chinese will be garbled and requires encoding conversion)
- * The usage method is as follows
- * $excel = new Excel();
- * $excel->addHeader(array('Column 1', 'Column 2','Column 3','Column 4'));
- * $excel->addBody(
- array(
- array('Data 1','Data 2','Data 3','Data 4 '),
- array('data1','data2','data3','data4'),
- array('data1','data2','data3','data4') ,
- array('data1','data2','data3','data4')
- )
- );
- * $excel->downLoad();
- */
- class Excel{
- private $head;
- private $body;
-
- /**
- *
- * @param type $arr one-dimensional array
- */
- public function addHeader($arr){
- foreach($arr as $headVal){
- $headVal = $this->charset($headVal);
- $this->head .= "{$headVal}t ";
- }
- $this->head .= "n";
- }
-
- /**
- *
- * @param type $arr two-dimensional array
- */
- public function addBody($arr){
- foreach($arr as $arrBody){
- foreach($arrBody as $bodyVal){
- $bodyVal = $this->charset($bodyVal);
- $this->body .= "{$bodyVal}t ";
- }
- $this->body .= "n";
- }
- }
-
- /**
- * Download excel file
- */
- public function downLoad($filename=''){
- if(!$filename)
- $filename = date('YmdHis',time()).'.xls';
- 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;
- }
-
- /**
- * Encoding conversion
- * @param type $string
- * @return string
- */
- public function charset($string){
- return iconv("utf-8", "gb2312", $string);
- }
- }
- ?>
复制代码
|