PHP導出Excel
這些天在使用PHPExcel導出數據時,5000條數據居然掛了。後來跟同事聊聊,有些明悟,PHPExcel作了不少處理,我在這裏理解爲渲染,就會暫用過多的空間,‘膨脹’的空間致使內存暫用過大,就掛了。其實只要咱們只是簡單的導出操做,沒有必要使用PHPExcel。大牛給了我這個程序,還沒搞清楚原理(若是有小夥伴知道,請不吝賜教哦!),貼出代碼:php
-
-
-
-
-
-
- public 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 .="<table border=1><head>".$titlename."</head>";
- $str .= $title;
- 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 );
- }
-
原理不是太懂,就是將html的表格轉換excel的表格;此種方法適應於設置各類單元格的顯示,合併,只需設置html的table,設置css就能導出各式各樣的excel模板。css
實例以下:
導出一個帶表頭,表頭帶顏色,設置字體大小,居中,排版適中;html
- $dataResult = array();
- $headTitle = "XX保險公司 優惠券贈送記錄";
- $title = "優惠券記錄";
- $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;' >合做商戶</th>
- <th style='width:70px;' >會員卡號</th>
- <th style='width:70px;'>車主姓名</th>
- <th style='width:150px;'>手機號</th>
- <th style='width:70px;'>車牌號</th>
- <th style='width:100px;'>優惠券類型</th>
- <th style='width:70px;'>優惠券名稱</th>
- <th style='width:70px;'>優惠券面值</th>
- <th style='width:70px;'>優惠券數量</th>
- <th style='width:70px;'>贈送時間</th>
- <th style='width:90px;'>截至有效期</th>
- </tr>";
- $filename = $title.".xls";
- $this->excelData($dataResult,$titlename,$headtitle,$filename);
提供案列供參考,具體程序能夠作更好的封裝處理。web
加油各位,加油本身,天行健!app