我需要将 mysql 表导出为 Excel 格式。我已经尝试过,但我仍然无法获得正确的格式。谁能帮我解决这个问题。我在下面附上了我的 php 函数。
<body>
<?php
function export_excel_csv()
{
$conn = mysql_connect("localhost","itsup739_uaquiz","itsup739_uaquiz");
$db = mysql_select_db("itsup739_uaquizDB",$conn);
$sql = "SELECT * FROM results";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\\t";
}
while($row = mysql_fetch_row($rec))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
{
$data = "\\n No Record Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
//echo $header;
}
export_excel_csv();
?>
请点击链接查看输出。