/**
* Excel導出
* @param $fileName(文件名)
* @param $headArr (表頭)
* @param $data (每一行的數(shù)據(jù))
* @throws \PHPExcel_Exception
* @throws \PHPExcel_Reader_Exception
*/
function getExcel($fileName,$headArr,$data){
include_once (THINK_PATH."Library/Vendor/phpexcel/PHPExcel.php");
include_once (THINK_PATH."Library/Vendor/phpexcel/PHPExcel/Writer/Excel2007.php");
include_once (THINK_PATH."Library/Vendor/phpexcel/PHPExcel/Writer/Excel5.php");
include_once (THINK_PATH."Library/Vendor/phpexcel/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}.xlsx";
//創(chuàng)建新的PHPExcel對象
$objPHPExcel = new \PHPExcel();
$objProps = $objPHPExcel->getProperties();
//設置表頭
$key = ord("A");
$key2 = ord("A");
$colum2 = '';
$objActSheet = $objPHPExcel->getActiveSheet();
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
foreach($headArr as $v){
$colum = chr($key);
$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum2.$colum.'1', $v);
if($key 90){
$key += 1;
}else{
$key = ord("A");
$colum2 = chr($key2);
$key2++;
}
}
//exit;
$column = 2;
foreach($data as $key => $rows){ //行寫入
$span = ord("A");
$span2 = ord("A");
$j2 = '';
foreach($rows as $keyName=>$value){// 列寫入
$j = chr($span);
//$objActSheet->setCellValue($j.$column, $value);
//把每個單元格設置成分文本類型
//dump($j2.$j.$column);
$objActSheet->setCellValueExplicit($j2.$j.$column,$value,\PHPExcel_Cell_DataType::TYPE_STRING);
if($span 90){
$span += 1;
}else{
$span = ord("A");
$j2 = chr($span2);
$span2++;
}
}
$column++;
}
// exit;
$fileName = iconv("utf-8", "gb2312", $fileName);
//重命名表
$objPHPExcel->getActiveSheet()->setTitle('Simple');
//設置活動單指數(shù)到第一個表,所以Excel打開這是第一個表
$objPHPExcel->setActiveSheetIndex(0);
//將輸出重定向到一個客戶端web瀏覽器(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');
// if(!empty($_GET['excel'])){
// $objWriter->save('php://output'); //文件通過瀏覽器下載
// }else{
// $objWriter->save($fileName); //腳本方式運行,保存在當前目錄
// }
$objWriter->save('php://output');
exit;
}