最近要寫個項目,由於項目中導出excel太多,因此寫個類便於使用。
<?php /* *@使用方法。 *引入類庫。 * $excel = news excelC(); *$excel->fileName = '文件名稱';//設置文件名稱,默認為時間戳 *$excel->format = '2007';//文件類型,默認為2007,其他為excel5 *$record = array( 'delKey'=>array('id','addTime','status'),//如果數據$data中有不需要顯示的列,可以在此說明。刪除不需要導出的鍵值 'sort' =>array( 'keyName'=>array('subjectName','flag'),//按keyName列排序,如果不存在則不排序。 //'reorder'=>'DESC',//排序方式,DESC為倒序,ASC為正序。如果keyName存在則排序keyName,如果不存在則按數組的鍵名排序,如果reorder不存在則不排序 ),//排序 如果sort存在則排序,否則不排序,如果keyName存在則按設置排序,如果不存在則按字符排序,如果reorder不存在或為空或為DES則正序,等於DESC為倒序。 'excelStyle' =>array( 'setName'=>'Arial',//字體樣式 'setSize'=>'12',//字體大小 ),//表格全局樣式 'title' =>array('tableName'=>'學科列表','center'=>true,'direction'=>'right','merge'=>'2','setSize'=>'30'),//標題,center垂直,direction為合並方向。right,left,up,down。 merge為合並幾個單元格,setSize為字體大小 'data' =>array( array('tableName'=>'科目名稱','width'=>'30','setName'=>'宋體','setSize'=>'20','background'=>'red','textColor'=>'white','bold'=>true,'underline'=>true,'borderColor'=>'cyan','center'=>true,), array('tableName'=>'學科','width'=>'50','center'=>true),//顏色表是:black,white,red,green,blue,yellow,magenta,cyan ),//表名稱 tableName為名稱,width為表格寬度,setName為字體樣式,background為背景顏色,textColor為字體顏色,bold為加粗,underline為下劃線,borderColor為邊框顏色. 'merge' =>array( //'flag'=>array('keyword'=>'初','direction'=>'right','merge'=>'2'),merge的鍵值為需要處理數據數組的鍵值,keyword為如果存在此關鍵字才執行其他樣式操作,如果keyword不存在則執行所有鍵值為flag的單元格。 'all'=>array('width'=>'30','setName'=>'宋體','setSize'=>'20','background'=>'red','textColor'=>'white','bold'=>true,'underline'=>true,'borderColor'=>'cyan','center'=>true,), ),// );//導出配置 *$excel->export($record,$data);//$record為導出配置,$data為數據庫的數據,$data可以為數組,也可以為對象。 * * * */ $address = dirname(dirname(__FILE__)).'/PHPExcel'; include $address.'/PHPExcel.class.php'; include $address.'/PHPExcel/Writer/Excel2007.php'; include $address.'/PHPExcel/Writer/Excel5.php'; include $address.'/PHPExcel/IOFactory.php'; /**************************** *生成excel文檔。 */ class excelC { public $format = '2007';//轉換格式,默認為2007版本,其他版本,請輸入不是2007的數字 public $fileName;//文件名稱默認為時間戳。 private $objExcel; private $letters; public function __construct() { $this->fileName = time(); $this->fileTitle = '導出數據'; $this->objExcel = new PHPExcel(); $this->letters = $this->letter(); } //導出excel的屬性 private function attribute(){ $this->objExcel->getProperties()->setCreator("力達行有限公司");//創建人 $this->objExcel->getProperties()->setLastModifiedBy("力達行有限公司");//最後修改人 $this->objExcel->getProperties()->setTitle("導出數據");//標題 $this->objExcel->getProperties()->setSubject("導出數據");//題目 $this->objExcel->getProperties()->setDescription("數據導出");//描述 $this->objExcel->getProperties()->setKeywords("office 導出");//關鍵字 $this->objExcel->getProperties()->setCategory("excel");//種類 } //設置表(如果只有一個sheet可以忽略該函數,將默認創建。) private function sheet(){ $this->objExcel->setActiveSheetIndex(0);//設置當前的表 $this->objExcel->getActiveSheet()->setTitle('excel');//設置表名稱。 } /*************************** *導出excel *@attr $record為表頭及樣式設置 *@attr $data為需要導出的數據 */ public function export($record=array(),$data=array()){ if(!$data)return false; if(!is_array($record))return false;//表樣式及其他設置 //處理獲取到的數據 $data = $this->maniData($record,$data); //獲取整體樣式。 $this->excelData($record,$data); //$this->objExcel->getActiveSheet()->setCellValue('A1', '季度'); $this->down();//導出下載 } /* *處理表格 */ private function excelData(&$record,&$data){ $this->attribute();//設置屬性 $this->sheet();//設置表 $this->whole($record);//設置整體樣式 $this->tableHeader($record);//設置表格頭。 $this->tableContent($record,$data);//設置表格 $this->excelTitle($record,2);//設置標題 } /* *設置表格整體樣式 */ private function whole(&$record){ if(!array_key_exists('excelStyle',$record))return false; $excelStyle = $record['excelStyle']; $default = $this->objExcel->getDefaultStyle(); if(array_key_exists('setName',$excelStyle)) $default->getFont()->setName($excelStyle['setName']);//設置字體樣式 if(array_key_exists('setSize',$excelStyle)) $default->getFont()->setSize($excelStyle['setSize']);//設置字體大小 } /* *設置標題 */ private function excelTitle($record,$num){ $titleL = $this->letters[0]; if(!array_key_exists('title',$record))return false; $this->appOintStyle($titleL ,1,$record['title']); } /* *設置表格頭。 */ private function tableHeader($record){ if(!array_key_exists('data',$record))return false; $objExcel = $this->objExcel; $letters = $this->letters; if(!is_array($record['data']))return false; $i = 0; $hang = 2; foreach($record['data'] as $k=>$v){ $this->appOintStyle($letters[$i],$hang,$v); $i++; } } private function setCellValue($letter,$data){ if(@$data) $this->objExcel->getActiveSheet()->setCellValue($letter, $data);//填充值 return $this; } private function getColumnDimension($letter,$data){ if(@$data) $this->objExcel->getActiveSheet()->getColumnDimension($letter)->setWidth($data);//設置寬度 return $this; } private function setName($letter,$data){ if(@$data) $this->objExcel->getActiveSheet()->getStyle($letter)->getFont()->setName($data);//設置字體 return $this; } private function setSize($letter,$data){ if(@$data) $this->objExcel->getActiveSheet()->getStyle($letter)->getFont()->setSize($data);//設置字體大小 return $this; } private function background($letter,$data){ if(@$data){ $this->objExcel->getActiveSheet()->getStyle($letter)->getFill()->getStartColor()->setARGB($this->backColor($data)); $this->objExcel->getActiveSheet()->getStyle($letter)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);//設置背景色樣式,無樣式將不顯示背景色。 } return $this; } private function textColor($letter,$data){ if(@$data){ $this->objExcel->getActiveSheet()->getStyle($letter)->getFont()->getColor()->setARGB($data);//字體顏色 } return $this; } private function setBold($letter,$data){ if(@$data){ $this->objExcel->getActiveSheet()->getStyle($letter)->getFont()->setBold(true);//加粗 } return $this; } private function setUnderline($letter,$data){ if(@$data){ $this->objExcel->getActiveSheet()->getStyle($letter)->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);//下劃線 } return $this; } private function border($letter,$data){ if(@$data){ $styleThinBlackBorderOutline = array( 'borders' => array ( 'outline' => array ( 'style' => PHPExcel_Style_Border::BORDER_THIN, //設置border樣式 'color' => array ('argb' => $data), //設置border顏色 ), ), ); $this->objExcel->getActiveSheet()->getStyle($letter)->applyFromArray($styleThinBlackBorderOutline); } return $this; } /* *合並 */ private function mergeCells($letters,$hang,$direction,$merge){ $merge = $merge-1; if($merge > 0 && $direction){ //print_r($this->letters); $l = array_flip($this->letters); $ln = $l[$letters]; switch ($direction) { case 'left': $signal = $this->letters[($ln-$merge)].$hang.':'.$letters.$hang; break; case 'right': $signal = $letters.$hang.':'.$this->letters[($ln+$merge)].$hang; break; case 'up': $signal = $letters.($hang-$merge).':'.$letters.$hang; break; case 'down': $signal = $letters.$hang.':'.$letters.($hang+$merge); break; default: $signal = ''; } if($signal){ $this->objExcel->getActiveSheet()->mergeCells($signal); } } return $this; } /* *垂直居中 */ private function setVertical($letter,$data){ if($data){ $this->objExcel->getActiveSheet()->getStyle($letter)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); $this->objExcel->getActiveSheet()->getStyle($letter)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); } return $this; } /* *設置顏色 */ private function backColor($color){ $array = array( 'black' => 'FF000000', // System Colour #1 - Black 'white' => 'FFFFFFFF', // System Colour #2 - White 'red' => 'FFFF0000', // System Colour #3 - Red 'green' => 'FF00FF00', // System Colour #4 - Green 'blue' => 'FF0000FF', // System Colour #5 - Blue 'yellow' => 'FFFFFF00', // System Colour #6 - Yellow 'magenta' => 'FFFF00FF', // System Colour #7- Magenta 'cyan' => 'FF00FFFF', // System Colour #8- Cyan ); if(array_key_exists($color,$array)){ return $array[$color]; } else { return false; } } /* *設置表 */ private function tableContent(&$record,&$data){ $objExcel = $this->objExcel; $letters = $this->letters; if(array_key_exists('merge',$record)) $merge = $record['merge']; else $merge = ''; $hang = 2; foreach($data as $k=>$v){ $i=0; $hang++; foreach($v as $kk=>$vv){ $this->setCellValue($letters[$i].$hang, $vv);//設置內容 $this->Appoint($kk,$vv,$letters[$i],$hang,$merge); $i++; } } } /* *設置表指定樣式 */ private function Appoint($kk,$vv,$letters,$hang,$merge){ if(!$merge)return false; if(array_key_exists($kk,$merge)){ $v = $merge[$kk]; if(array_key_exists('keyword',$v)){ if(strpos($vv,$v['keyword']) > -1){ $this->appOintStyle($letters,$hang,$v); } } else { $this->appOintStyle($letters,$hang,$v); } } else if(array_key_exists('all',$merge)){ $v = $merge['all']; if(array_key_exists('keyword',$v)){ if(strpos($vv,$v['keyword']) > -1){ $this->appOintStyle($letters,$hang,$v); } } else { $this->appOintStyle($letters,$hang,$v); } } } /* *終極樣式 */ private function appOintStyle($letters,$hang,$v){ $this ->setCellValue($letters.$hang,@$v['tableName']) ->getColumnDimension($letters,@$v['width']) ->setName($letters.$hang,@$v['setName']) ->setSize($letters.$hang,@$v['setSize']) ->background($letters.$hang,@$v['background']) ->textColor($letters.$hang,$this->backColor(@$v['textColor'])) ->setBold($letters.$hang,@$v['bold']) ->setUnderline($letters.$hang,@$v['underline']) ->border($letters.$hang,$this->backColor(@$v['borderColor'])) ->mergeCells($letters,$hang,@$v['direction'],@$v['merge']) ->setVertical($letters.$hang,@$v['center']); } /* *應為字母列表 */ public function letter(){ return array('A','B','C','D','F','G','H','I','G','K','L','M','N','O','P','Q','R','S','T','U','V','W','H','Y','Z'); } /**************************** *處理數據,排序及刪除字段 */ private function maniData($record,$data){ if(!$data)return false; if(!is_array($record))return false;//表樣式及其他設置 $data = $this->objectToArray($data);//對象轉數組 $delKey = (array_key_exists('delKey',$record))?$record['delKey']:'';//是否刪除關鍵字 $sort = (array_key_exists('sort',$record))?$record['sort']:'';//是否排序 $data = $this->delSort($data,$delKey,$sort); return $data; } /**************************** *對象轉數組 */ private function objectToArray($data){ if(!$data)return false; $data = (array)$data; foreach($data as $k=>$v){ if(is_object($v) || is_array($v)){ $data[$k] = (array)$this->objectToArray($v); } } return $data; } /**************************** *刪除鍵值,並排序 */ private function delSort($data,$delKey='',$sort=''){ if(!$data)return false; $array = array(); foreach($data as $k=>$v){ //刪除數據中的某個鍵值 $delData = $this->delData($v,$delKey); //按設定鍵值排序 $sortData = $this->sortData($delData,$sort); $array[$k] = $sortData; } return $array; } /**************************** *刪除鍵值 */ public function delData($data,&$delKey){ if($delKey){ foreach($delKey as $delVal){ if(array_key_exists($delVal,$data))//判斷鍵值是否存在 unset($data[$delVal]);//清除鍵名。 } } return $data; } /**************************** *鍵值排序 */ public function sortData($data,&$sort){ $array = array(); if($sort){ if(array_key_exists('keyName',$sort)){ $keyName = $sort['keyName']; if(array_key_exists('reorder',$sort)){ if($sort['reorder'] == 'DESC'){ krsort($keyName); } else if($sort['reorder'] == 'ASC'){ ksort($keyName); } } foreach($keyName as $vn){ $array[$vn] = (array_key_exists($vn,$data))?$data[$vn]:''; } } else { if(array_key_exists('reorder',$sort)){ if($sort['reorder'] == 'DESC'){ krsort($data); } else if($sort['reorder'] == 'ASC'){ ksort($data); } $array = $data; } } } return $array; } //導出下載 private function down(){ if($this->format == '2007'): header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); $excel = 'Excel2007'; else: header('Content-Type: application/vnd.ms-excel'); $excel = 'Excel5'; endif; header("Content-Disposition: attachment; filename=\"$this->fileName\""); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($this->objExcel, $excel); $objWriter->save('php://output'); } }
你好,其實非常簡單的問題,就是將要打印的頁面的頭設置為!
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=php100.xls");
這樣,浏覽器就直接下載該文件。將文件裡面的
<table>
<tr>
<td>內容</td>
<tr>
</table>
就直接放在Excel的表格裡面了!
詳情,請參考php100的教程。php100對這個問題有一個視頻教程。
下載地址: www.php100.com/...0.html
總結 php導出Excel php導入Excel PhpExcel使用說明 PhpExcel使用手冊2009/03/06 上午 02:37方法一:特點,簡單,省心,
<?php
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=test_data.xls");
$tx='表頭';
echo $tx."\n\n";
//輸出內容如下:
echo "姓名"."\t";
echo "年齡"."\t";
echo "學歷"."\t";
echo "\n";
echo "張三"."\t";
echo "25"."\t";
echo "本科"."\t";
?>
方法二: 引用google code中推薦的小類庫(大體同方法一,比較復雜點)
code.google.com/p/php-excel/downloads/list
方法三: PHPEXCEL 類庫,功能強大,支持win Excel2003 ,Win Excel2007.
www.codeplex.com/PHPExcel
<?
//設置PHPExcel類庫的include path
set_include_path('.'. PATH_SEPARATOR .
'D:\Zeal\PHP_LIBS' . PATH_SEPARATOR .
get_include_path());
/**
* 以下是使用示例,對於以 //// 開頭的行是不同的可選方式,請根據實際需要
* 打開對應行的注釋。
* 如果使用 Excel5 ,輸出的內容應該是GBK編碼。
*/
require_once 'PHPExcel.php';
// uncomment
////require_once 'PHPExcel/Writer/Excel5.ph......余下全文>>