gpt4 book ai didi

php - 将 MySQL 数据导出到 Excel 会出错

转载 作者:搜寻专家 更新时间:2023-10-30 23:47:13 25 4
gpt4 key购买 nike

在使用 PHP 将数据导出到 excel 时,它被导出,但我不断收到这些错误消息:

  1. “'database.xls' 的文件格式和扩展名不匹配。文件可能已损坏或不安全。除非您相信其来源,否则请勿打开它。您是否仍要打开它?”<
  2. “Excel 已检测到‘database.xls’是 SYLK 文件,但无法加载它。文件有错误或不是 SYLK 文件格式。单击“确定”以尝试以其他格式打开。”

点击确定几次后,它确实打开了,但我想知道是否有一种简单的方法可以解决这个问题。

这是代码(使用 John Peter 的 code ):

<?php
//db connection data
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). " <br>" . mysql_errno());
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
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 = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>

最佳答案

这些错误与用于创建文件的编程语言无关。这两个错误都是由 MS Excel 中的一个错误引起的。
MSDN:

When you try to open a text or comma separated variable (CSV) file, you receive the following error message:

SYLK: File format is not valid

This problem occurs when you open a text or CSV file and the first two characters of the file are the letters ID (uppercase).

有关完整详细信息,请参阅 https://support.microsoft.com/en-in/help/215591/-sylk-file-format-is-not-valid-error-message-when-you-open-a-file-in-e

关于php - 将 MySQL 数据导出到 Excel 会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com