本文主要和大家分享PHP建立或匯出Excel資料表格的方法,主要以一段代碼和大家分享,希望能協助到大家。
$filename = "order_".date('Y-m-d').".xls"; $header = array('訂單編號','訂單類型','會員ID','總加工費','商品總價','郵費','應付金額','訂單狀態','下單時間'); $index = array('order_sn','kind','mid','other_price','goods_price','shipping_price','order_amount','order_status','regtime'); $$orderlist = M('table')->where($where)->order('id')->select();create_xls($orderlist,$filename,$header,$index);/*** 數組轉xls格式的excel檔案* @param array $data 要匯出的數組格式的資料 * @param string $filename 匯出的Excel表格式資料表的檔案名稱 * @param array $header Excel表格的表頭 * @param array $index $list數組中與Excel表格表頭$header中每個項目對應的欄位的名字(key值) * 比如: $header = array('編號','姓名','性別','年齡'); * $index = array('id','username','sex','age'); * $data = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24)); * 樣本資料: $strexport = array( array(NULL, 2010, 2011, 2012), array('Q1', 12, 15, 21), array('Q2', 56, 73, 86), array('Q3', 52, 61, 69), array('Q4', 30, 32, 0), ); */function create_xls($data,$filename='simple.xls',$header,$indexKey){ ini_set('max_execution_time', '0'); Vendor('PHPExcel.PHPExcel'); $filename=str_replace('.xls', '', $filename).'.xls'; $phpexcel = new PHPExcel(); $phpexcel->getProperties() ->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") ->setTitle("Office 2007 XLSX Test Document") ->setSubject("Office 2007 XLSX Test Document") ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") ->setKeywords("office 2007 openxml php") ->setCategory("Test result file"); //組合儲存格的內容 foreach ($data as $k=>$row) { foreach ($indexKey as $key=>$value){ //這裡是設定儲存格的內容 $strexport[$k][$key]=$row[$value]; } } array_unshift($strexport,$header); $phpexcel->getActiveSheet()->fromArray($strexport); $phpexcel->getActiveSheet()->setTitle('Sheet1'); $phpexcel->setActiveSheetIndex(0); header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename=$filename"); header('Cache-Control: max-age=0'); header('Cache-Control: max-age=1'); header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header ('Pragma: public'); // HTTP/1.0 $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5'); $objwriter->save('php://output'); exit;}