1、簡介
如何利用最簡單粗糙暴力的方法將資料寫入Excel檔案中呢?
因為ms word和excel的文檔都支援html文字格式設定,因此我們可以基於這個原理採用html文字格式設定進行資料的輸出。
在html中,我們只需要將資料照著所想要的順序放進相應的html表格中即可。
我們採用PHP進行資料擷取整理以及構造相應的html文本,最後通過位元組流輸出下載到使用者本地。
2、代碼
直接上代碼,這是一個很簡單的程式,裡面都帶有注釋了。
ExportExcel.class.php檔案
<?phpclass ExportExcel{ /** * @desc 將資料匯出到Excel中 * @param $data array 設定表格式資料 * @param $titlename string 設定head * @param $title string 設定表頭 * @param $filename 設定預設檔案名稱 * @return 將字串輸出,即輸出位元組流,下載Excel檔案 */ public function excelData($data,$titlename,$title,$filename){ #xmlns即是xml的命名空間 $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>"; #以下構建一個html類型格式的表格 $str .= $title; $str .="<table border=1><head>".$titlename."</head>"; foreach ($data 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 ); }}?>
<?php$obj=new ExportExcel();$data = array( array('a11','a22','a33'), array('b11','b22','b33'), array('c11','c22','c33'), array('d11','d22','d33'), array('e11','e22','e33'), array('f11','f22','f33'), ); $excelHead = "這個是Excel表格標題"; $title = "我的Excel表"; #檔案命名$headtitle= "<tr><th colspan='3' >{$excelHead}</th></tr>"; $titlename = "<tr> <th style='width:70px;'>表格1</th> <th style='width:70px;'>表格2</th> <th style='width:70px;'>表格3</th> </tr>"; $filename = $title.".xls"; $obj->excelData($data,$titlename,$headtitle,$filename); ?>
3、測試
點擊訪問:
下載該Excel檔案
成功後查看該檔案:
進入後Excel提示說該檔案格式與尾碼名不一致,這也間接說明了我們所匯出來的Excel檔案僅僅只是個外表是Excel(實質是html檔案),格式上並不是Excel檔案。
點擊是進入查看裡面的內容,上看去挺像Excel的嘛,哈哈。就醬紫
更改尾碼名為html進入查看:
你瞧,實質就是html檔案嘛,只是Excel支援該格式而已。
4、參考文獻
《PHP匯出Excel》
(以上是自己的一些見解,若有不足或者錯誤的地方請各位指出)