php將資料寫入excel
阿新 • • 發佈:2019-02-11
//header("Content-type: text/html; charset=utf-8");
//include_once 'PHPExcel.php';
/**
* 生成excel* @param $list
*/
public function excel($list,$excelName='brand') {
// 建立新的PHPExcel物件
$objPHPExcel = new PHPExcel();
// 設定屬性
$objPHPExcel->getProperties()->setCreator("ctos")
->setLastModifiedBy("ctos")
->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");
// 字型寬度
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
// 設定行高度
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);
$objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
// 設定水平居中
$objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
// 表頭
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', '品牌')
->setCellValue('B1', '系列');
// 內容
$i = 2;
foreach($list as $key => $item ){
foreach($item as $k => $v ){
$objPHPExcel->getActiveSheet(0)->setCellValue('A'.$i, $key);
$objPHPExcel->getActiveSheet(0)->setCellValue('B'.$i, $v['goname'].'__'.$v['name']);
++$i;
}
}
// 重新命名工作表
$objPHPExcel->getActiveSheet()->setTitle('車資訊');
// 第一張工作表組活躍表索引,所以Excel開啟這是第一個表
$objPHPExcel->setActiveSheetIndex(0);
// 輸出
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $excelName . '.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}