<?php
class PHPExcel{  
	public $link = null;  
	/***************************************************************************  
	* $mapping：数组格式头信息$map=array('No','Name','Email','Age');  
	* $datalist：数据库查出来的结果集  
	* $fileName：Excel文件名称  
	* return：Excel格式文件  
	**************************************************************************/  
	public function toExcel($mapping,$datalist,$fileName,$trtitle) {
		header("Content-type:application/vnd.ms-excel");  
		//header("Content-Disposition:filename=".iconv('gb2312', 'utf-8', $fileName).".xls");  
		header("Content-Disposition:filename=".$fileName.".xls");  
		echo'<html xmlns:o="urn:schemas-microsoft-com:office:office"  
		xmlns:x="urn:schemas-microsoft-com:office:excel"  
		xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">  
		<head>  
		<meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">  
		<meta http-equiv=Content-Type content="text/html; charset=UTF-8">  
		<!--[if gte mso 9]>
		<xml>  
		<x:ExcelWorkbook>  
		<x:ExcelWorksheets>  
		<x:ExcelWorksheet>  
		<x:Name></x:Name>  
		<x:WorksheetOptions>  
		<x:DisplayGridlines/>  
		</x:WorksheetOptions>  
		</x:ExcelWorksheet>  
		</x:ExcelWorksheets>  
		</x:ExcelWorkbook>  
		</xml>
		<![endif]-->  
		</head>  
		<body link=blue vlink=purple leftmargin=0 topmargin=0>';  
		echo'<table border="1" cellspacing="0" cellpadding="0" width="1090">';
		if($trtitle){
			echo'<tr>';
				echo"<td colspan='".count($mapping)."' style='font-weight:bold;color:#09F;height:50px;text-align:center;font-size:30px;font-family:simhei'>".$trtitle."</td>";
			echo'</tr>';
		}
		if(is_array($mapping)){
			if(count($mapping) == count($mapping, COUNT_RECURSIVE)){
				echo'<tr>';
				foreach($mapping as $key=>$val){
					echo"<td style='background-color:#ddd;font-weight:bold;'>".$val."</td>";
				}
				echo'</tr>';  
			}else{
				echo'<tr>';
				foreach($mapping as $key=>$val){
					if(is_array($val)){
						echo"<td style='background-color:#ddd;font-weight:bold;' colspan='".count($val)."'>".$key."</td>";
					}else{
						echo"<td style='background-color:#ddd;font-weight:bold;' rowspan='2'>".$val."</td>";
					}
				}
				echo'</tr><tr>';
				foreach($mapping as $key=>$val){
					if(is_array($val)){
						foreach($val as $k=>$t){
							echo"<td style='background-color:#ddd;font-weight:bold;'>".$t."</td>";
						}
					}
				}
				echo'</tr>';
			}
		} 
		foreach($datalist as $k=>$v){  
			echo'<tr>';  
			foreach($v as $key=>$val){  
				if(is_numeric($val) && strlen($val)>=14){  
					echo"<td style='vnd.ms-excel.numberformat:@'>".$val."</td>"; //大于14位的数字转换成字符串输出(如身份证)  
				}else{  
					echo"<td>".$val."</td>";  
				}  
			}  
			echo'</tr>';  
		}  
		echo'</table>';  
		echo'</body>';  
		echo'</html>';  
	}  
}
?>