匯出方法
public function csv(String $sFileName,Array $aTitle, $oQuery, Closure $closure)
{
set_time_limit(0);
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'. $sFileName .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$fp = fopen('php://output', 'a');
fwrite($fp, "\xEF\xBB\xBF");
fputcsv($fp, $aTitle);
$accessNum = $oQuery->count();
$perSize = 10000;
$pages = ceil($accessNum / $perSize);
for($i = 1; $i <= $pages; $i++) {
$oCollection = $oQuery->forPage($i,$perSize)->get();
foreach($oCollection as $obj) {
$rowData = $closure($obj);
fputcsv($fp, $rowData);
}
unset($oCollection);
if (ob_get_level() > 0) {
ob_flush();
}
}
fclose($fp);
exit();
}
使用
$aTitle=[
'編號','使用者姓名','郵箱','建立時間'
];
$csvFileName = '使用者資料統計.csv';
$oQuery = DB::table("users")->select('id','name','email','created_at');
$this->csv($csvFileName,$aTitle,$oQuery,function ($obj){
return [
$obj->id , $obj->name ,$obj->email, $obj->created_at
];
});
注意事項
- 表頭Tile不要以英文字母開頭,否則開啟會有檔案損壞的不友好提示
本作品採用《CC 協議》,轉載必須註明作者和本文連結