导出表结构:
mysql> desc user ; +----------+--------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(20) | NO | | NULL | | | sex | char(10) | YES | | male | | | intro | varchar(500) | YES | | NULL | | | birthday | timestamp | NO | | 2018-04-18 08:15:30 | | +----------+--------------+------+-----+---------------------+----------------+ 5 rows in set (0.02 sec)
要导出上面这种表结构,可以使用如下代码:
<?php define("DIR",dirname(__FILE__)); include DIR."/PHPExcel/PHPExcel.php"; $mysqli = new Mysqli("127.0.0.1","root","123456","test"); $mysqli_result = $mysqli->query("desc user");
//为了防止取出的数据的字段位置改变,优先使用关联数组形式 $res = $mysqli_result->fetch_all(MYSQLI_ASSOC); $objExcel = new PHPExcel(); $objSheet = $objExcel->getActiveSheet(); $objSheet->setTitle("demo"); $objSheet->setCellValue("A1","Field")->setCellValue("B1","Type") ->setCellValue("C1","Null")->setCellValue("D1","Key") ->setCellValue("E1","Default")->setCellValue("F1","Extra"); foreach($res as $k=>$v){ $index = $k + 2;//注意一下,是从2开始 $objSheet->setCellValue("A".$index,$v["Field"])->setCellValue("B".$index,$v["Type"]) ->setCellValue("C".$index,$v["Null"])->setCellValue("D".$index,$v["Key"]) ->setCellValue("E".$index,$v["Default"])->setCellValue("F".$index,$v["Extra"]); } $objWriter = PHPExcel_IOFactory::createWriter($objExcel,"Excel2007"); $objWriter->save(DIR."/demo.xlsx"); ?>
命令行运行之后,Excel表格内容如下:
有一点要注意,如果一个字段的默认值是NULL,那么上面可以看到,是没有写入的,可以通过下面的方法完成。
导出表内容
其实导出表的内容和导出表的结构,过程是一样的,基本没变化,只需要改一下SQL语句即可。