1. 安装PHPExcel
composer require phpoffice/phpexcel
在使用时,需要引入classes目录下的PHPExcel.php的PHPExcel类以及classes\PHPExcel\IOFactory.php的PHPExcel_IOFactory类。
具体项目实例在项目经验中查看。
2. 使用步骤
header('Content-Type:text/html; charset=utf-8');//转换一下格式 避免乱码
$objExcel = new \PHPExcel();
//set document Property
$objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
$objActSheet = $objExcel->getActiveSheet();
$key = ord("A");
$letter =explode(',',"A,B,C,D,E,F,G,H,I,J");
//填充表头信息
$arrHeader = array('序号',"类型",'名字','性别','身份证号','代表队','代表队简称',"组别","项目","联系方式");
$lenth = count($arrHeader);
for($i = 0;$i < $lenth;$i++) {
$objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
};
//填充表格信息
foreach($result as $k=>$v){
$k +=2;
$sex = ($v['sex_id'] == 1)?"男":"女";
$group = $v['groupName']??"";
$itemName = $v['itemName']?? "";
$mobile = $v['mobile']?? "";
$objActSheet->setCellValue('A'.$k,$v['id']);
$objActSheet->setCellValue('B'.$k, $v['typeName']);
$objActSheet->setCellValue('C'.$k, $v['name']);
$objActSheet->setCellValue('D'.$k, $sex);
$objActSheet->setCellValue('E'.$k, $v['idCard']." "."\t");
$objActSheet->setCellValue('F'.$k, $v['delegationName']);
$objActSheet->setCellValue('G'.$k, $v['abbreviation']);
$objActSheet->setCellValue('H'.$k, $group);
$objActSheet->setCellValue('I'.$k, $itemName);
$objActSheet->setCellValue('J'.$k, $mobile);
// 表格高度
$objActSheet->getRowDimension($k)->setRowHeight(20);
}
$width = array(10,15,20,25,30);
//设置表格的宽度
$objActSheet->getColumnDimension('A')->setWidth($width[1]);
$objActSheet->getColumnDimension('B')->setWidth($width[3]);
$objActSheet->getColumnDimension('C')->setWidth($width[2]);
$objActSheet->getColumnDimension('D')->setWidth($width[4]);
$objActSheet->getColumnDimension('E')->setWidth($width[4]);
$objActSheet->getColumnDimension('F')->setWidth($width[4]);
$objActSheet->getColumnDimension('G')->setWidth($width[4]);
$objActSheet->getColumnDimension('H')->setWidth($width[4]);
$objActSheet->getColumnDimension('I')->setWidth($width[3]);
$objActSheet->getColumnDimension('J')->setWidth($width[4]);
//下载的文件夹名
$outfile = time()."-报名人员.xlsx";
ob_end_clean();
$path=FCPATH.'/static/excel/';//upload为目标文件夹
if (!is_dir($path)){
$oldumask = umask(0);
mkdir($path,0777,true);
umask($oldumask);
}
$objWriter->save(str_replace('.php','.xls',$path.$outfile));