<?php include './PHPExcel/PHPExcel.php'; include './PHPExcel/PHPExcel/Writer/Excel2007.php'; //或者include 'PHPExcel/Writer/Excel5.php'; 用于输出.xls的 //创建一个excel $objPHPExcel = new PHPExcel(); $letter = range('A','Z'); //表头 $header_arr = [ 'id', '标题', '作者', 'url', ]; //创建人 $objPHPExcel->getProperties()->setCreator("brady.wang"); //最后修改人 $objPHPExcel->getProperties()->setLastModifiedBy("brady.wang"); //标题 $objPHPExcel->getProperties()->setTitle("用户"); //题目 $objPHPExcel->getProperties()->setSubject("获取用户"); //描述 $objPHPExcel->getProperties()->setDescription("获取数据库用户列表"); //关键字 $objPHPExcel->getProperties()->setKeywords("user"); //设置当前的sheet $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->setTitle('用户名'); //设置宽度 for ($i=0; $i < count($header_arr) ; $i++) { $objPHPExcel->getActiveSheet()->setCellValue("$letter[$i]1", "$header_arr[$i]"); $objPHPExcel->getActiveSheet()->getColumnDimension($letter[$i])->setWidth(25); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(45); $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5); $objPHPExcel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID); $objPHPExcel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->getStartColor()->setRGB('FF0000'); } $conn = mysql_connect("192.168.33.50","root",'root'); mysql_select_db('test',$conn); mysql_query('set names utf8'); $res = mysql_query("select id,article_title,article_author,url from content"); while ($row = mysql_fetch_row($res)) { $result[] = $row; } for($i = 2; $i<count($result) + 2;$i++) { $j = 0; foreach($result[$i-2] as $v) { $objPHPExcel->getActiveSheet()->setCellValue("$letter[$j]$i", $v); $j++; } } // // 输出Excel表格到浏览器下载 header('Content-Type: application/vnd.ms-excel;charset=utf-8'); header('Content-Disposition: attachment;filename="abc.xls"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed 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 = new PHPExcel_Writer_Excel5($objPHPExcel); $objWriter->save('php://output');