爲什麼說高性能?
使用過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);
}