PHP資料匯出Excel
阿新 • • 發佈:2018-12-26
需要將php資料匯出Exel表格中,可以用PHPExcel,但是也有更快的方法,但是會出現些小問題
比如:
/* *處理Excel匯出 *@param $datas array 設定表格資料 *@param $titlename string 設定head *@param $title string 設定表頭 */ /** * */ function excelData($datas,$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 .= $title; $str .="<table border=1><head>".$titlename."</head>"; foreach ($datas as $key=> $rt ) { $str .= "<tr>"; foreach ( $rt as $k => $v ) { $str .= "<td>{$v}</td>"; } $str .= "</tr>\n"; } $str .= "</table></body></html>"; 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 ); }
例項:
$dataResult=[[1,2,3,4,5,6]]; //匯出資料 $headTitle = "測試excel專案記錄"; $title = "測試excel"; $headtitle= "<tr style='height:50px;border-style:none;'><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >{$headTitle}</th></tr>"; $titlename = "<tr> <th style='width:70px;' >專案1</th> <th style='width:70px;' >專案2</th> <th style='width:70px;'>專案3</th> <th style='width:150px;'>專案4</th> <th style='width:70px;'>專案5</th> <th style='width:70px;'>專案6</th> </tr>"; $filename = $title.".xls"; excelData($dataResult,$titlename,$headtitle,$filename);
實踐可以使用,自己封裝