gpt4 book ai didi

php - 使用 PHP 将 MySQL 数据保存到 Excel 工作表

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

我正在尝试将数据从数据库写入可下载的 Excel 工作表。该代码正在运行,因为它下载具有所需名称的文件。但是,如果我打开 Excel 工作表,单元格为空,并且我的数据不在工作表中。

这是我的代码

require_once('include/connect_pdo.php');
$myschool = $_POST['country'];

$findschool = $conn->prepare("SELECT Query");
$findschool->execute();

$filename = "Name";
$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";
}

最佳答案

这解决了我的问题。

Header('Content-Description: File Transfer');
Header('Content-Encoding: UTF-8');
Header('Content-type: text/csv; charset=UTF-8');
Header('Content-Disposition: attachment; filename=' . '$filename' . '.csv');
echo "\xEF\xBB\xBF"; // UTF-8 BOM

$output = fopen("php://output", "w");
fputcsv($output, array('Number1', 'Number 2'));
$findschool = $conn->prepare("SELECT Query Here);
$findschool->execute();
while ($result = $findschool->fetch(PDO::FETCH_ASSOC)) {

fputcsv($output, $result);
}
fclose($output);

关于php - 使用 PHP 将 MySQL 数据保存到 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49492447/

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