导出excel数据

青旅半醒 2022-07-15 07:30 306阅读 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(

  1. 'DB\_Server'=>$DB\_Server,
  2. 'DB\_Username'=>$DB\_Username,
  3. 'DB\_Password'=>$DB\_Password,
  4. 'DB\_DBName'=>$DB\_DBName,
  5. '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++) {

  1. echo mysql\_field\_name($result,$i) . "\\t";

}

print(“\n”);

$i = 0;

while($row = mysql_fetch_row($result)) {

  1. $schema\_insert = "";
  2. for($j=0; $j<mysql\_num\_fields($result);$j++) \{
  3. if(!isset($row\[$j\]))
  4. $schema\_insert .= "NULL".$sep;
  5. elseif ($row\[$j\] != "")
  6. $schema\_insert .= "$row\[$j\]".$sep;
  7. else
  8. $schema\_insert .= "".$sep;
  9. \}
  10. $schema\_insert = str\_replace($sep."$", "", $schema\_insert);
  11. $schema\_insert .= "\\t";
  12. $schema\_insert = iconv("utf-8", "gb2312", $schema\_insert);
  13. print(trim($schema\_insert));
  14. print "\\n";
  15. $i++;

}

exit;

?>

连接数据库

<?php

class connection

{

  1. const MSGTYPE\_TEXT = 'text';
  2. private $DB\_Server = "127.0.0.1";
  3. private $DB\_Username = "root";
  4. private $DB\_Password = "123456";
  5. private $DB\_DBName = "tp\_dudj";
  6. private $DB\_TBLName = "think\_role";
  7. public function \_\_construct($options)
  8. \{
  9. $this->DB\_Server = isset($options\['DB\_Server'\])?$options\['DB\_Server'\]:'';
  10. $this->DB\_Username = isset($options\['DB\_Username'\])?$options\['DB\_Username'\]:'';
  11. $this->DB\_Password = isset($options\['DB\_Password'\])?$options\['DB\_Password'\]:'';
  12. $this->DB\_DBName = isset($options\['DB\_DBName'\])?$options\['DB\_DBName'\]:'';
  13. $this->DB\_TBLName = isset($options\['DB\_TBLName'\])?$options\['DB\_TBLName'\]:'';
  14. \}
  15. public function connect()
  16. \{
  17. $con = mysql\_connect($this->DB\_Server,$this->DB\_Username,$this->DB\_Password) or die("数据库连接失败");
  18. mysql\_select\_db($this->DB\_DBName,$con);
  19. mysql\_query("set names utf8",$con);
  20. return $con;
  21. \}

}

?>

发表评论

表情:
评论列表 (有 0 条评论,306人围观)

还没有评论,来说两句吧...

相关阅读