標籤:data cell blank file iconv his pex gb2312 out
官網http://phpexcel.codeplex.com/下載最新PHPExcel放到tp架構的核心目錄ThinkPHP裡面的Vendor下
1 public function test(){ 2 $xlsName = "使用者"; 3 4 //注意 數組第一個欄位必須是小寫 數組第二個(欄位標題)根據你的情況填寫 5 $xlsCell = array( 6 array(‘欄位1‘,‘帳號序列‘), 7 array(‘欄位2‘,‘登入賬戶‘), 8 array(‘欄位3‘,‘賬戶暱稱‘), 9 array(‘欄位4‘,‘真實姓名‘),10 array(‘欄位5‘,‘身份‘)11 );12 $xlsModel = M(‘表名‘);13 $xlsData = $xlsModel->Field(‘欄位1,欄位2,欄位3,欄位4,欄位5‘)->select();14 $this->exportExcel($xlsName,$xlsCell,$xlsData);15 }
//匯出excel $expTitle:檔案名稱 $expCellName:表頭標題 $expTableData:資料來源
1 public function exportExcel($expTitle,$expCellName,$expTableData){ 2 vendor("phpexcel.Classes.PHPExcel"); 3 $xlsTitle = iconv(‘utf-8‘, ‘gb2312‘, $expTitle);//檔案名稱 4 $fileName = $xlsTitle;//or $xlsTitle 檔案名稱可根據自己情況設定 5 $cellNum = count($expCellName); 6 $dataNum = count($expTableData); 7 8 $objPHPExcel = new \PHPExcel(); 9 $cellName = array(‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,‘O‘,‘P‘,‘Q‘,‘R‘,‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘,‘AA‘,‘AB‘,‘AC‘,‘AD‘,‘AE‘,‘AF‘,‘AG‘,‘AH‘,‘AI‘,‘AJ‘,‘AK‘,‘AL‘,‘AM‘,‘AN‘,‘AO‘,‘AP‘,‘AQ‘,‘AR‘,‘AS‘,‘AT‘,‘AU‘,‘AV‘,‘AW‘,‘AX‘,‘AY‘,‘AZ‘);10 11 $objPHPExcel->getActiveSheet(0)->mergeCells(‘A1:‘.$cellName[$cellNum-1].‘1‘);//合併儲存格12 $objPHPExcel->setActiveSheetIndex(0)->setCellValue(‘A1‘, $expTitle.‘ 匯出時間:‘.date(‘Y-m-d H:i:s‘)); 13 for($i=0;$i<$cellNum;$i++){14 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].‘2‘, $expCellName[$i][1]); 15 } 16 // Miscellaneous glyphs, UTF-8 17 for($i=0;$i<$dataNum;$i++){18 for($j=0;$j<$cellNum;$j++){19 $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);20 } 21 } 22 23 header(‘pragma:public‘);24 header(‘Content-type:application/vnd.ms-excel;charset=utf-8;name="‘.$xlsTitle.‘.xls"‘);25 header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新視窗列印inline本視窗列印26 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘); 27 $objWriter->save(‘php://output‘); 28 exit; 29 }
thinkphp匯出excel功能封裝