標籤:phpexcel head code position factory out actor down web
php Excel 檔案匯出
phpExcel 官網 http://phpexcel.codeplex.com/
/** * 匯出特定檔案 * 依據詳細情況而定 */ public function download(){ //1. 從資料庫來擷取相應的二維數組 $alist = array(...); $list = $alist; $data = array();//2. 設定xls的 表頭名 $headArr = array("排名","姓名","手機","獲獎","參與時間"); if(false === empty($list)){ $i=0; foreach ($list as $key => $val){ //組裝相應的儲存格A。B。C,D。。。
$data[$i] = array( ($i+1), //A $val['name'], //B $val['tel'], //C $val['award'], //D ... ); $i++; } }else{ $data[0] = array('暫無相關記錄。'); } $fileName = "test-excel_"; $this->explodexls($data,$headArr,$fileName); } /** * 工具函數 處理 xls 檔案匯出 * @param $data array() 相應的tbody 資料 * @param $headArr array() 相應的thead 資料 * @param $fileName string 指定的匯出檔案名稱 * @return xls格式 檔案自己主動匯出 */ public function explodexls($data,$headArr,$fileName){//注意這裡換成相應的根資料夾 找到絕對路徑 $dir = __dir__.'/../../../../public'; require_once $dir.'/excel/PHPExcel.php'; require_once $dir.'/excel/PHPExcel/Writer/Excel2007.php'; require_once $dir.'/excel/PHPExcel/Writer/Excel5.php'; include_once $dir.'/excel/PHPExcel/IOFactory.php'; if(empty($data) || !is_array($data)){ die("data must be a array"); } if(empty($fileName)){ exit; } $date = date("Y_m_d",time()); $fileName .= "_{$date}.xls"; //建立新的PHPExcel對象 $objPHPExcel = new PHPExcel(); $objProps = $objPHPExcel->getProperties(); //設定表頭 $key = ord("A"); foreach($headArr as $v){ $colum = chr($key); $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v); $key += 1; } $column = 2; $objActSheet = $objPHPExcel->getActiveSheet(); foreach($data as $key => $rows){ //行寫入 $span = ord("A"); foreach($rows as $keyName=>$value){// 列寫入 $j = chr($span); $objActSheet->setCellValue($j.$column, $value); $span++; } $column++; } //$fileName = iconv("utf-8", "gb2312", $fileName); //重新命名表 $objPHPExcel->getActiveSheet()->setTitle('Simple'); //設定活動單指數到第一個表,所以Excel開啟這是第一個表 $objPHPExcel->setActiveSheetIndex(0); //將輸出重新導向到一個clientweb瀏覽器(Excel2007) header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header("Content-Disposition: attachment; filename=\"$fileName\""); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); //檔案通過瀏覽器下載 exit; }
php excel檔案匯出之phpExcel擴充庫