thinkphp3.2结合PHPExcel导出数据库里所有表的结构,含注释
先看图
一、控制器代码如下:
public function out(){
$sql="show tables";//读取库里所有的表
$result=M()->query($sql);
foreach ($result as $k => $v) {
$k++;
$_sql="SHOW FULL COLUMNS FROM ".$v['Tables_in_'.C('DB_NAME')];
$data[][0]=array("表 {$k}.{$v['Tables_in_test']} 表",'','','','','','');
$data[][1]=array("字段","类型","校对","NULL","键","默认","额外","权限","注释");
$data[]=M()->query($_sql);
$data[][]=array();
}
//导入PHPExcel类库
import("Org.Util.PHPExcel");
import("Org.Util.PHPExcel.Writer.Excel5");
import("Org.Util.PHPExcel.IOFactory.php");
$filename="test_excel";
$headArr=array("ID","字段","类型","NULL","键","默认","额外","注释");
$this->getExcel($filename,$headArr,$data);
}
private function getExcel($fileName,$headArr,$data){
//对数据进行检验
if(empty($data) || !is_array($data)){
die("data must be a array");
}
$date = date("Y_m_d",time());
$fileName .= "_{$date}.xls";
//创建PHPExcel对象,注意,不能少了\
$objPHPExcel = new \PHPExcel();
$objProps = $objPHPExcel->getProperties();
//设置表头
$key = ord("A");
$column = 2;
$objActSheet = $objPHPExcel->getActiveSheet();
foreach ($data as $ke => $row) {
foreach($row as $key => $rows){ //行写入
$span = ord("B");
foreach($rows as $keyName=>$value){// 列写入
$j = chr($span);
$objActSheet->setCellValue($j.$column, $value);
$span++;
}
$column++;
}
}
$fileName = iconv("utf-8", "gb2312", $fileName);
//设置活动单指数到第一个表,所以Excel打开这是第一个表
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=\"$fileName\"");
header('Cache-Control: max-age=0');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output'); //文件通过浏览器下载
exit;
}
二、下载附件,把里面的文件及文件夹放到tp的核心目录 ThinkPHP\Library\Org\Util 下
三、数据库的配置项自行配置
四、访问out方法,就可以导出excel表了
五、想要更多的功能自行修改. OVER