转自:http://blog.chinaunix.net/uid-11600035-id-2866120.html
经过测试,非常好用。
<?php
function xlsBOF() {echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteNumber($Row, $Col, $Value) {
$Value = iconv("UTF-8", "gb2312", $Value); //加上本语句,解决导出excel文件乱码问题20110629
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$Value = iconv("UTF-8", "gb2312", $Value); //加上本语句,解决导出excel文件乱码问题20110629
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
try{
$pdo = new PDO('mysql:host=127.0.0.1;dbname=test','root','123456');
}catch(PDOexception $e){
echo $e->getMessage();
exit();
}
$sql = "select * from user";
$stmt = $pdo->query($sql);
// 文件头
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
header("Content-Disposition: attachment;filename=test统计表.xls ");
//header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
//iconv("utf-8", "gb2312", $filename);//解决文件引起的乱码".xls\"");
header("Content-Transfer-Encoding: binary ");
// 向表中添加数据
xlsBOF();
xlsWriteLabel(0,0,"主键id"); //(行号,列号,值)从第1行开始写标题
xlsWriteLabel(0,1,"姓名");
xlsWriteLabel(0,2,"用户uid");
$xlsRow = 1;//从第2行开始写值
while($array = $stmt->fetch(PDO::FETCH_ASSOC)){
xlsWriteNumber($xlsRow,0,$array['id']);
xlsWriteLabel($xlsRow,1,$array['name']);
xlsWriteLabel($xlsRow,2,$array['uid']);
$xlsRow++;
}
xlsEOF();
exit();
?>