PHPExcel是一个第三方类库,可以很方便地导出excel文档。
首先要使用composer引入这个包:
composer require phpoffice/phpexcel
下面是一个demo:
$data1 = array(
['id'=>1,'username'=>'test1','phone'=>'18881515151'],
['id'=>2,'username'=>'test2','phone'=>'18881515152'],
['id'=>3,'username'=>'test3','phone'=>'18881515153'],
);
$sheetkey = array(
'id'=>'A',
'username'=>'B',
'phone'=>'C',
);
$sheettitle = array(
'id'=>'ID',
'username'=>'答题人',
'phone'=>'联系方式',
);
exportExcel($data,$sheetkey,$sheettitle,'问卷答题情况');
function exportExcel($data,$sheetkey,$sheettitle,$sheetName){
//include_once "phpexcel/PHPExcel.php";
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("phpexcel")
->setLastModifiedBy("phpexcel")
->setTitle($sheetName)
->setSubject($sheetName)
->setDescription($sheetName)
->setKeywords($sheetName);
$objPHPExcel->setActiveSheetIndex(0);
$objSheet = $objPHPExcel->getActiveSheet();
$objSheet->setTitle($sheetName);
foreach ($sheettitle as $key => $value) {
$objSheet->setCellValue($sheetkey[$key].'1',$value);
}
unset($value);
$data = array_values($data);
for ($i=0;$i<count($data);$i++) {
foreach ($data[$i] as $key => $value) {
$objSheet->setCellValue($sheetkey[$key].($i+2),$value);
}
unset($value);
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$sheetName.'.xlsx"');
header('Cache-Control: max-age=0');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
在浏览器运行代码就会下载excel文件了