Php到csv导出在单独的单元格中使用逗号分隔符

时间:2014-06-04 09:09:10

标签: php mysql excel csv export

我在这里找到了这个代码,我应该将它用于我的网站。但是虽然一切看起来都不错,但不知何故分隔符不起作用。正如你所看到的,我把逗号(,)作为分隔符,当在mysql中有(|)时,我把它改为逗号再次在单元格中分开。

但是,我得到的结果是一切都在第一个细胞中。有逗号,但它没有分开。所以,如果我点击excel数据>分隔符并用逗号分隔 - 然后就可以了。

如何解决这个问题?我是新手,所以这里有一个简单的具体变化吗?

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$columnName = array();
if (mysql_num_rows($result) > 0) 
{
    while ($row = mysql_fetch_assoc($result)) 
    {
        $columnName[] = $row['Field'];
        $i++;
    }
}
$columnName[] .= "\n";
$needle = "|";
$values = mysql_query("SELECT * FROM ".$table." where id=".$id."");
while ($rowr = mysql_fetch_row($values)) 
{
    for ($j=0;$j<$i;$j++) 
    {
        $colName = $columnName[$j];
        $count = strlen($rowr[$j]) - strlen(str_replace(str_split($needle), "", $rowr[$j]));
        if ($count > 1)
        {
            for($p=0;$p<$count;$p++)
            {
                $colName .= ",";
            }
            $columnName[$j] = $colName;
            $csv_output_column_names .= $columnName[$j].", ";
            $csv_output_column_values .= str_replace("|",",",$rowr[$j]).", ";
        }
        else 
        {
            $csv_output_column_names .= $columnName[$j]. ", ";
            $csv_output_column_values .= $rowr[$j] .", ";
        }
    }
    $csv_output_column_values .= "\n";
}
$csv_output = $csv_output_column_names."\n".$csv_output_column_values;
$filename = $file."_".date("Y-m-d");
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

0 个答案:

没有答案