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();