//使用PHP将Mysql数据表导出到Excel中
<?php
$db = 'test';
$table = 'article';
header("content-type:text/html;charset=utf-8");
@mysql_connect('localhost','root','123456');
mysql_set_charset('utf8');
mysql_select_db($db);
$sql = "select * from $table";
$res = mysql_query($sql);
$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("content-type:application/$file_type");
header("content-Disposition: attachement; filename=$table.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");
$time = date("Y-m-d H:i");
$title = "数据库名:$db,数据表名:$table,备份日期:$time";
echo "$title\n";
$sep = "\t";
for ($i=0; $i < mysql_num_fields($res); $i++) {
echo mysql_field_name($res,$i)."\t";
}
print("\n");
$i = 0;
while ($row = mysql_fetch_row($res)) {
$schema_insert = "";
for($j = 0;$j < mysql_num_fields($res); $j++){
if (!isset($row[$j])) {
$schema_insert .= "NULL".$sep;
} elseif($row[$j] != ""){
$schema_insert .= "$row[$j]".$sep;
} else {
$schema_insert .= "".$sep;
}
}
$schema_insert .= "\t\n";
echo $schema_insert;
$i++;
}