gpt4 book ai didi

mysql - 将 MySQL 数据导出到 Excel(以逗号分隔)

转载 作者:行者123 更新时间:2023-11-29 10:29:53 24 4
gpt4 key购买 nike

我有这个代码:

$sql = "SELECT  ...
FROM ...
WHERE ...;

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password);
$Db = @mysql_select_db($DB_DBName, $Connect);
$result = @mysql_query($sql,$Connect);
$file_ending = "xls";

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");

$sep = "\t"; //tabbed character
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";
}

如果每列上的数据不包含逗号,它就可以完美工作。但是当它有逗号时,它将成为分隔符,导出的列和数据与SQL结果不一样。

如何忽略 MySQL 结果上的逗号,以便将其导出为 Excel 文件?谢谢。

最佳答案

您只需在文本周围添加引号即可:

$sql = "SELECT  ...
FROM ...
WHERE ...";

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password);
$Db = @mysql_select_db($DB_DBName, $Connect);
$result = @mysql_query($sql,$Connect);
$file_ending = "xls";

header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");

$sep = "\t"; //tabbed character
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; // changes on this line
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";
}

关于mysql - 将 MySQL 数据导出到 Excel(以逗号分隔),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47604842/

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