PHP導出Excel

PHP導出Excel

這些天在使用PHPExcel導出數據時,5000條數據居然掛了。後來跟同事聊聊,有些明悟,PHPExcel作了不少處理,我在這裏理解爲渲染,就會暫用過多的空間,‘膨脹’的空間致使內存暫用過大,就掛了。其實只要咱們只是簡單的導出操做,沒有必要使用PHPExcel。大牛給了我這個程序,還沒搞清楚原理(若是有小夥伴知道,請不吝賜教哦!),貼出代碼:php

  1. /* 
  2. *處理Excel導出 
  3. *@param $datas array 設置表格數據 
  4. *@param $titlename string 設置head 
  5. *@param $title string 設置表頭 
  6. */ 
  7. public function excelData($datas,$titlename,$title,$filename)
  8. $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>"
  9. $str .="<table border=1><head>".$titlename."</head>"
  10. $str .= $title
  11. foreach ($datas as $key=> $rt

  12. $str .= "<tr>"
  13. foreach ( $rt as $k => $v

  14. $str .= "<td>{$v}</td>"

  15. $str .= "</tr>\n"

  16. $str .= "</table></body></html>"
  17. header( "Content-Type: application/vnd.ms-excel; name='excel'" ); 
  18. header( "Content-type: application/octet-stream" ); 
  19. header( "Content-Disposition: attachment; filename=".$filename ); 
  20. header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); 
  21. header( "Pragma: no-cache" ); 
  22. header( "Expires: 0" ); 
  23. exit( $str ); 

  24.  

原理不是太懂,就是將html的表格轉換excel的表格;此種方法適應於設置各類單元格的顯示,合併,只需設置html的table,設置css就能導出各式各樣的excel模板。css

實例以下:
導出一個帶表頭,表頭帶顏色,設置字體大小,居中,排版適中;html

  1. $dataResult = array(); //todo:導出數據(自行設置) 
  2. $headTitle = "XX保險公司 優惠券贈送記錄"
  3. $title = "優惠券記錄"
  4. $headtitle= "<tr style='height:50px;border-style:none;><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >{$headTitle}</th></tr>"
  5. $titlename = "<tr> 
  6. <th style='width:70px;' >合做商戶</th> 
  7. <th style='width:70px;' >會員卡號</th> 
  8. <th style='width:70px;'>車主姓名</th> 
  9. <th style='width:150px;'>手機號</th> 
  10. <th style='width:70px;'>車牌號</th> 
  11. <th style='width:100px;'>優惠券類型</th> 
  12. <th style='width:70px;'>優惠券名稱</th> 
  13. <th style='width:70px;'>優惠券面值</th> 
  14. <th style='width:70px;'>優惠券數量</th> 
  15. <th style='width:70px;'>贈送時間</th> 
  16. <th style='width:90px;'>截至有效期</th> 
  17. </tr>"
  18. $filename = $title.".xls"
  19. $this->excelData($dataResult,$titlename,$headtitle,$filename); 

提供案列供參考,具體程序能夠作更好的封裝處理。web

加油各位,加油本身,天行健!app

相關文章
相關標籤/搜索