public function excel()
{
// 标题
$head=array('用户编号','上班日期','签到时间','签退时间');
// 内容
$csvArr[]=array('用户编号1','上班日期1','签到时间1','签退时间1');
$csvArr[]=array('用户编号2','上班日期2','签到时间2','签退时间2');
// 下载
$this->DownLoadCsvBySQL($csvArr,$title,date("YmdHis").'.csv');
}
/**
* PHP通过sql生成CSV文件并下载
* @param string $sql 查询sql,结果为二维数组
* @param array $title 数据,CSV文件标题
* @param string $filename 文件名
*/
function DownLoadCsvBySQL($data,$title,$filename='DownLoad.csv')
{
ob_start();
$file = fopen("php://output", 'w');
fwrite($file,chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($file, $title);
foreach($data as $k=>$v) fputcsv($file, $v);
Header("Content-type: application/octet-stream"); #通过这句代码客户端浏览器就能知道服务端返回的文件形式
Header("Accept-Ranges: bytes"); #告诉客户端浏览器返回的文件大小是按照字节进行计算的
Header("Content-Disposition: attachment; filename=".$filename); #告诉浏览器返回的文件的名称
echo fread($file,999999);
fclose($file);
}

下载文件