读取数据库数据并输成excel
db.php
<?php /** * Created by PhpStorm. * User: 清风徐来 * Date: 2018/5/12 * Time: 15:49 */ require dirname(__FILE__)."./dbconfig.php";//引入配置文件 class db{ public $conn=null; public function __construct($config) { $this->conn = mysql_connect($config['host'], $config['username'], $config['password']) or die(mysql_error());//连接数据库 mysql_select_db($config['database'], $this->conn) or die(mysql_error()); mysql_query("set names " . $config['charset']) or die(mysql_error()); } /* * 根据传入sql语句 查询mysql结果集 * */ public function getResult($sql){ $resource=mysql_query($sql,$this->conn) or die(mysql_error()); $res=array(); while (($row=mysql_fetch_assoc($resource))!=false){ $res[]=$row; } return $res; } /* * **/ public function getData(){ $sql="select id,username,password from cl_user"; $res=self::getResult($sql); return $res; } // $this->conn=mysqli_connect($config['host'],$config['username'],$config['password']),$config['database']; // mysqli_query("set names ".$config['charset']); }
export.php
<?php /** * Created by PhpStorm. * User: 清风徐来 * Date: 2018/5/12 * Time: 16:06 */ $dir=dirname(__FILE__); //查找当前脚本所在路径 require $dir."/db.php";//引入mysql操作类文件 require $dir."/PHPExcel/PHPExcel.php";//引入PHPExcel $db=new db($phpexcel); //实例化db类 连接数据库 $objPHPExcel = new PHPExcel();//实例化PHPExcel类, for($i=1;$i<=100;$i++){ if ($i>1){ $objPHPExcel->createSheet();//创建新的内置表 } $objPHPExcel->setActiveSheetIndex($i-1); //把新 $objSheet=$objPHPExcel->getActiveSheet();//获取当前活动sheet $objSheet->setTitle('数据'); //給sheet 标题命名 $data=$db->getData(); $objSheet->setCellValue("A1","id")->setCellValue("B1","分数")->setCellValue("C1","班级");//设定标题 $j=2; foreach ($data as $key=>$val){ //填充数据 $objSheet->setCellValue("A".$j,$val['id'])->setCellValue("B".$j,$val['username'])->setCellValue("C".$j,$val['password']); $j++; } $objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5'); //设定输出文件格式 $objWriter->save($dir."/export_1.xls"); //保存目录 } ?>