这几天在项目中用到了用php导出xls,给大家分享一下部分代码:
public 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;
}
$contents=$dr->query($sql);//从数据库取出数据
$str = “Date\tDate1\tDate2\n”;//表头——\t分隔
$str = iconv(‘utf-8′,’gb2312′,$str);//转码
foreach($contents as $k=>$v){
$a1 = iconv(‘utf-8′,’gb2312′,$v['date']);
$a2 = iconv(‘utf-8′,’gb2312′,$v['date1']);
$a3 = iconv(‘utf-8′,’gb2312′,$v['date2']);
$str .= $a1.”\t”.$a2.”\t”.$a3.”\t\n”;//拼接每一行数据
}
$filename = date(‘YmdHis’).’.xls’;//导出文件的名
$this->exportExcel($filename,$str);//调用上面的方法,生成文件