【发布时间】:2013-03-19 22:07:23
【问题描述】:
我正在尝试将我的 MySQL 数据导入 Excel 文件,但我遇到了 Excel 单元格的问题。我所有的文本都放在一个单元格中,我希望将每一行的值放在单独的 Excel 单元格中。这是我的代码:
$queryexport = ("
SELECT username,password,fullname FROM ecustomer_users
WHERE fk_customer='".$fk_customer."'
");
$row = mysql_fetch_assoc($queryexport);
$result = mysql_query($queryexport);
$header = '';
for ($i = 0; $i < $count; $i++){
$header .= mysql_field_name($result, $i)."\t";
}
while($row = mysql_fetch_row($result)){
$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 = "\nno matching records found\n";
}
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");
// output data
echo $header."\n".$data;
mysql_close($conn);`
【问题讨论】:
-
与您的问题无关,但您应该真正使用数组来构建文件的行。然后你只需要使用
implode将元素粘合在一起。当您想附加分隔符时,这样可以省去检查当前行缓冲区是否为空的麻烦。 -
@Miklos - 为什么使用内爆? PHP 提供内置函数 fputcsv() 用于写入 CSV/TSV/etc 文件
-
@Mark 感谢提醒,PHP 不是我的主要技能,所以我不知道那个功能。