php 匯出資料到excel類

來源:互聯網
上載者:User
將資料匯出到excel當中,歡迎大家拍磚
  1. /**
  2. * 匯出到excel檔案(一般匯出中文的都會亂碼,需要進行編碼轉換)
  3. * 使用方法如下
  4. * $excel = new Excel();
  5. * $excel->addHeader(array('列1','列2','列3','列4'));
  6. * $excel->addBody(
  7. array(
  8. array('資料1','資料2','資料3','資料4'),
  9. array('資料1','資料2','資料3','資料4'),
  10. array('資料1','資料2','資料3','資料4'),
  11. array('資料1','資料2','資料3','資料4')
  12. )
  13. );
  14. * $excel->downLoad();
  15. */
  16. class Excel{
  17. private $head;
  18. private $body;
  19. /**
  20. *
  21. * @param type $arr 一維數組
  22. */
  23. public function addHeader($arr){
  24. foreach($arr as $headVal){
  25. $headVal = $this->charset($headVal);
  26. $this->head .= "{$headVal}\t ";
  27. }
  28. $this->head .= "\n";
  29. }
  30. /**
  31. *
  32. * @param type $arr 二維數組
  33. */
  34. public function addBody($arr){
  35. foreach($arr as $arrBody){
  36. foreach($arrBody as $bodyVal){
  37. $bodyVal = $this->charset($bodyVal);
  38. $this->body .= "{$bodyVal}\t ";
  39. }
  40. $this->body .= "\n";
  41. }
  42. }
  43. /**
  44. * 下載excel檔案
  45. */
  46. public function downLoad($filename=''){
  47. if(!$filename)
  48. $filename = date('YmdHis',time()).'.xls';
  49. header("Content-type:application/vnd.ms-excel");
  50. header("Content-Disposition:attachment;filename=$filename");
  51. header("Content-Type:charset=gb2312");
  52. if($this->head)
  53. echo $this->head;
  54. echo $this->body;
  55. }
  56. /**
  57. * 編碼轉換
  58. * @param type $string
  59. * @return string
  60. */
  61. public function charset($string){
  62. return iconv("utf-8", "gb2312", $string);
  63. }
  64. }
  65. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.