一个简单易用的导出Excel类

转载自:http://www.umtry.com/201105/%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E6%98%93%E7%94%A8%E7%9A%84%E5%AF%BC%E5%87%BAexcel%E7%B1%BB.html5
<?php
class toExcel{
public $link = null;
function __construct(){
}
function conndb($confdb){
$this->link = pg_connect($confdb);
return $this->link;
}
/***************************************************************************
* $table:表名
* $mapping:数组格式头信息$map=array(‘No’,'Name’,'Email’,'Age’);
* $sql:sql语句
* $fileName:Excel文件名称
* return:Excel格式文件
**************************************************************************/
public function toExcel($mapping,$sql,$fileName) {
header(“Content-type:application/vnd.ms-excel”);
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=”0″ cellspacing=”0″ cellpadding=”0″>’;
echo’<tr>’;
if(is_array($mapping)) {
foreach($mapping as $key=>$val)
echo”<td style=’background-color:#09F;font-weight:bold;’>”.$val.”</td>”;
}
echo’</tr>’;
//数据库连接
if(!is_resource($this->link)) {
$this->conndb(DBCONF);
}
$query=pg_query($this->link,$sql);
while($rows=pg_fetch_assoc($query)){
echo’<tr>’;
foreach($rows 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>’;
}
}
?>

使用
$toexcel = new toExcel();
$toexcel->conndb(“host=localhost port=5432 dbname=super user=super password=super”);
$toexcel->toExcel($lable_arr,$sql,$excel_name);
posted @ 2011-06-29 17:50  煋火  阅读(513)  评论(0编辑  收藏  举报