首页 > php教程 > php手册 > PHP将数据库导出为excel表

PHP将数据库导出为excel表

WBOY
发布: 2016-06-06 20:08:28
原创
1407 人浏览过

?php /*连接数据库*/ $DB_Server = "localhost"; $DB_Username = "root"; $DB_Password = "123456"; $DB_DBName = "mydb"; //目标数据库名 $DB_TBLName = "mytable"; //目标表名 $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die(

/*连接数据库*/
$DB_Server = "localhost";
$DB_Username = "root";
$DB_Password = "123456";
$DB_DBName = "mydb";  //目标数据库名
$DB_TBLName = "mytable";  //目标表名
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect.");
mysql_query("Set Names 'utf8'");

$savename = date("YmjHis"); //导出excel文件名
$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Content-Type: application/$file_type;charset=utf8");
header("Content-Disposition: attachment; filename=".$savename.".$file_ending");
//header("Pragma: no-cache");

/*写入备注信息*/
$now_date = date("Y-m-j H:i:s");
$title = "数据库名:$DB_DBName,数据表:$DB_TBLName,备份日期:$now_date";
echo("$title\n");

/*查询数据库*/
$sql = "Select * from $DB_TBLName";
$ALT_Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database");
$result = @mysql_query($sql,$Connect) or die(mysql_error());

/*写入表字段名*/
for ($i = 0; $i  echo mysql_field_name($result,$i) . ",";
}
echo "\n";

/*写入表数据*/
$sep = ",\t";
while($row = mysql_fetch_row($result)) {
 $data = "";
  for($i=0; $i    if(!isset($row[$i]))
    $data .= "NULL".$sep; //处理NULL字段
   elseif ($row[$i] != "")
    $data .= "$row[$i]".$sep;
   else
    $data .= "".$sep; //处理空字段
  }
 echo $data."\n";
}
?>

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板