分享一個PHP高效能匯出excel的好方法
阿新 • • 發佈:2018-12-17
為什麼說高效能?
使用過phpoffice系列,也就是phpexcel這個非常著名的擴充套件,但是但是,匯出1000條以上的資料表,顯得非常吃力,嘗試使用php的cli模式,放到服務端匯出,又發現一個問題,記憶體洩漏,並且在執行幾次後記憶體超過.於是自己寫了個方法,匯出excel,效能遠超phpexcel外掛
原理是什麼?
簡單粗暴,組裝html成xls,比phpexcel內部內處理要快5倍左右,支援大資料量的匯出,具體根據你資料量和請求時間的多少而定.
//控制器內使用,組裝列表 //$list反正就是個陣列列表 $query = $model->find(); $list = $query->asArray()->all(); //列標題 $header = ['登入名','暱稱','角色','級別','狀態','最後登入時間','建立時間','交易賬號','姓名','訊息開關狀態','使用者積分','房間名稱','房間ID','是否VIP']; $datas = []; foreach ($list as $k => $v) { // $excel->HandleLarge($times); $datas[$k]['登入名'] = $v['user_loginname']; $datas[$k]['暱稱'] = $v['user_nickname']; } $name = '使用者匯出'; $this->ExcelPull($name, $header, $datas); //XLS匯出 /** $name string 檔名稱 $header array 列標題 $dataResult 陣列 **/ public function ExcelPull($name, $header, $dataResult) { //這一行沒啥用,根據具體情況優化下 $headTitle = "xx詳情"; $headtitle= "<tr style='height:50px;border-style:none;><td border=\"0\" style='height:90px;width:470px;font-size:22px;' colspan='11' >{$headTitle}</th></tr>"; $titlename = "<tr>"; foreach ($header as $v) { $titlename .= "<td>$v</td>"; } $titlename .= "</tr>"; $fileName = date("Y-m-d") . "-" . $name . ".xls"; $this->excelData($dataResult, $titlename, $headtitle, $fileName); } public function excelData($data, $titlename, $title, $filename) { $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>"; $str .="<table border=1>" . $titlename; $str .= ''; foreach ($data as $key => $rt) { $str .= "<tr>"; foreach ($rt as $v) { $str .= "<td >{$v}</td>"; } $str .= "</tr>\n"; } $str .= "</table></body></html>"; $str .= "<span>creator:".yii::$app->user->identity->user_loginname."</span>"; header("Content-Type: application/vnd.ms-excel; name='excel'"); header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=" . $filename); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); header("Expires: 0"); exit($str); }