PHPExcel导出主要代码记录
/* * 获取下一个列名 * 注意,此方法最多支持到两位 * */ function getNextColum($colum){ if(empty($colum))return 'A'; $key = ord(substr($colum,strlen($colum)-1,1)); if($key<90){ $str = strlen($colum)>1?substr($colum,0,1).chr($key+1):chr($key+1); }else{ $str = strlen($colum)>1?chr(ord(substr($colum,0,1))+1).'A':'AA'; } return $str; } function exportExcel(){ $keyValue = array( 'field_01' => '第一列标题', 'field_02' => '第二列标题', 'field_03' => '第三列标题', 'field_04' => '第四列标题', ); $list = array( array('field_01' => 'value_01', 'field_02' => 'value_02', 'field_03' => 'value_03', 'field_04' => 'value_04'), array('field_01' => 'value_01', 'field_02' => 'value_02', 'field_03' => 'value_03', 'field_04' => 'value_04'), array('field_01' => 'value_01', 'field_02' => 'value_02', 'field_03' => 'value_03', 'field_04' => 'value_04'), array('field_01' => 'value_01', 'field_02' => 'value_02', 'field_03' => 'value_03', 'field_04' => 'value_04') ); $this->import('PHPExcel'); $PHPExcel = new PHPExcel(); $fileName = iconv("utf-8", "GBK", 'excel文件名_导出时间(' . date('YmdHi', time()) . ').xlsx'); $colum = "A";//设置表头 foreach ($keyValue as $keys => $value) { $PHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $value); $PHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth(30); $colum = getNextColum($colum); } $row = 2; foreach ($list as $value) { $colum = "A";//设置表头 foreach ($keyValue as $v => $fieldContent) { $PHPExcel->setActiveSheetIndex(0)->setCellValueExplicit($colum . $row, empty($value[$v]) ? '--' : $value[$v], PHPExcel_Cell_DataType::TYPE_STRING); $PHPExcel->getActiveSheet()->getColumnDimension($colum)->setWidth(30); $colum = getNextColum($colum); } $row++; } header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header("Content-Disposition: attachment; filename=\"$fileName\""); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007'); $objWriter->save('php://output'); }