<?php
function exportExcel($filename,$content){header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/vnd.ms-execl");
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
echo $content;
}
$db=new PDO($dsn,'root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES \'UTF8\''));//实例化pdo对象
$res=$db->query("select * from student");//从数据库查询数据
$str = "姓名\t性别\t年龄\t\n";
$str = iconv('utf-8','gb2312',$str);//iconv() 是编码转换函数
while($row=$res->fetchAll()){
$name = iconv('utf-8','gb2312',$row['name']);
$sex = iconv('utf-8','gb2312',$row['sex']);
$str .= $name."\t".$sex."\t".$row['age']."\t\n";
}
$filename = date('Ymd').'.xls';
exportExcel($filename,$str); //生成excel表格