首先请先下载 PHPExcel 扩展包
代码内需要引入
<?php class Excal { /** * @param $data 数据内容 ,数组格式 具体格式 见底部 * @param string $title 文件名称 */ public function Excel($data, $title = 'excel') { /** * 引入 PhpEXCEL */ include_once('Phpexcel/PHPExcel.php'); error_reporting(E_ALL); date_default_timezone_set('Europe/London'); $objPHPExcel = new Phpexcel(); $objPHPExcel->getProperties()->setCreator("ABC")->setLastModifiedBy("ABC") ->setTitle($title) ->setSubject($title) ->setDescription($title) ->setKeywords("excel")->setCategory("result file"); $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $s = 0; foreach ($data['name'] as $v) { if ($s <= 25) { $objPHPExcel->setActiveSheetIndex()->setCellValue(substr($str, $s, 1) . '1', $v); } else { if ($s > 25 && $s <= 51) { $objPHPExcel->setActiveSheetIndex()->setCellValue(substr($str, 0, 1) . substr($str, $s - 26, 1) . '1', $v); } } $s++; } foreach ($data['value'] as $k => $v) { $sd = 0; foreach ($v as $ko => $vo) { if ($sd <= 25) { $objPHPExcel->setActiveSheetIndex()->setCellValue(substr($str, $sd, 1) . ($k + 2), $vo); } else { if ($sd > 25 && $sd <= 51) { $objPHPExcel->setActiveSheetIndex()->setCellValue(substr($str, 0, 1) . substr($str, $sd - 26, 1) . ($k + 2), $vo); } } $sd++; } } header('pragma:public'); header('Content-Type: application/vnd.ms-excel;charset=utf-8;name="' . $title . '.xls"'); header('Content-Disposition: attachment;filename="' . $title . '.xls"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit; } //数据格式如下 public function test(){ /** * 如果有非常长的数字 例如身份证号 或者 其他纯数字编号的,建议加上符号(;·等)在进行输出 */ $arr=array( 'name' => array('姓名','手机号','时间'), 'value' => array( '0'=>array( 'username'=>'小明', 'phone'=>'123', 'time'=>'2050.1.1' ), '1'=>array( 'username'=>'小红', 'phone'=>'123', 'time'=>'2050.1.1' ), '2'=>array( 'username'=>'小绿', 'phone'=>'123', 'time'=>'2050.1.1' ), ) ); $this->Excel($arr,'文件名称'); } } ?>