2019獨角獸企業重金招聘Python工程師標準>>>
思路:
1, 引入Excel類庫;
2, 創建一個模板;
3, 將數據填充進去;
4, 生成文件;
?
下面是一個簡單的示例
$phpExcelObj = new PHPExcel();
$titleMap = self::TITLE_MAP;
//設置表頭
$i = 0;
foreach ($titleMap as $key => $title) {$column = PHPExcel_Cell::stringFromColumnIndex($i);//向第$column列第一行, 寫入值$phpExcelObj->setActiveSheetIndex(0)->setCellValue($column . 1, $title); $i++;
}
//填充數據, key和表頭map的key一致
$data = [];
$j = 0;
foreach ($data as $row) {$i = 0;foreach ($titleMap as $key => $title) {$column = PHPExcel_Cell::stringFromColumnIndex($i);//向第$column列第j+2行, 寫入值 (因表頭占據第一行,所以第一個記錄從第二行開始)$phpExcelObj->setActiveSheetIndex(0)->setCellValue($column . ($j + 2), $row[$key]);$i++;}$j++;
}
//設置sheet名稱
$phpExcelObj->getActiveSheet()->setTitle('sheet_name');
$phpExcelObj->setActiveSheetIndex(0);header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//設置導出文件名
$fileName = '測試文件';
header(sprintf('Content-Disposition: attachment;filename="%s.xlsx"', $fileName));
header('Cache-Control: max-age=0');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: cache, must-revalidate');$writerObj = PHPExcel_IOFactory::createWriter($phpExcelObj, 'Excel2007');
$writerObj->save('php://output');exit();
?