导出excel数据 青旅半醒 2022-07-15 07:30 178阅读 0赞 <? /\* \*@author:dudj \*@time:20160331 \*@effect:通过按钮实现数据库数据的导出 \*/ include "connection.class.php"; $DB\_Server = '127.0.0.1'; $DB\_Username = 'root'; $DB\_Password = '123456'; $DB\_DBName = 'tp\_dudj'; $DB\_TBLName = 'think\_role'; $connection = new connection(array( 'DB\_Server'=>$DB\_Server, 'DB\_Username'=>$DB\_Username, 'DB\_Password'=>$DB\_Password, 'DB\_DBName'=>$DB\_DBName, 'DB\_TBLName'=>$DB\_TBLName, )); $con = $connection->connect(); //导出excel保存的名字 $savename = date("YmjHis"); //文件类型 $file\_type = "vnd.ms-excel"; //以什么结尾 $file\_ending = "xls"; //header头信息 header("Content-Type: application/$file\_type;charset=UTf-8"); header("Content-Disposition: attachment; filename=".$savename.".$file\_ending"); //备份日期 $now\_date = date("Y-m-j H:i:s"); $title = "数据库名:$DB\_DBName,数据表:$DB\_TBLName,备份日期:$now\_date"; //因为excel导出的数据 被查看的时候 是gbk的因此转码 $title = iconv("utf-8", "gb2312", $title); $sql = "Select \* from $DB\_TBLName"; $result = mysql\_query($sql,$con) or die(mysql\_error()); echo("$title\\n"); $sep = "\\t"; //mysql\_num\_fields 获取字段 for ($i = 0; $i < mysql\_num\_fields($result); $i++) \{ echo mysql\_field\_name($result,$i) . "\\t"; \} print("\\n"); $i = 0; while($row = mysql\_fetch\_row($result)) \{ $schema\_insert = ""; for($j=0; $j<mysql\_num\_fields($result);$j++) \{ if(!isset($row\[$j\])) $schema\_insert .= "NULL".$sep; elseif ($row\[$j\] != "") $schema\_insert .= "$row\[$j\]".$sep; else $schema\_insert .= "".$sep; \} $schema\_insert = str\_replace($sep."$", "", $schema\_insert); $schema\_insert .= "\\t"; $schema\_insert = iconv("utf-8", "gb2312", $schema\_insert); print(trim($schema\_insert)); print "\\n"; $i++; \} exit; ?> 连接数据库 <?php class connection \{ const MSGTYPE\_TEXT = 'text'; private $DB\_Server = "127.0.0.1"; private $DB\_Username = "root"; private $DB\_Password = "123456"; private $DB\_DBName = "tp\_dudj"; private $DB\_TBLName = "think\_role"; public function \_\_construct($options) \{ $this->DB\_Server = isset($options\['DB\_Server'\])?$options\['DB\_Server'\]:''; $this->DB\_Username = isset($options\['DB\_Username'\])?$options\['DB\_Username'\]:''; $this->DB\_Password = isset($options\['DB\_Password'\])?$options\['DB\_Password'\]:''; $this->DB\_DBName = isset($options\['DB\_DBName'\])?$options\['DB\_DBName'\]:''; $this->DB\_TBLName = isset($options\['DB\_TBLName'\])?$options\['DB\_TBLName'\]:''; \} public function connect() \{ $con = mysql\_connect($this->DB\_Server,$this->DB\_Username,$this->DB\_Password) or die("数据库连接失败"); mysql\_select\_db($this->DB\_DBName,$con); mysql\_query("set names utf8",$con); return $con; \} \} ?>
还没有评论,来说两句吧...