我使用通用算法来编写理论上适用于主要操作系统的CSV文件。但是,几周前客户端开始使用Mac,并且他们一直告诉我无法在Microsoft Excel 2008 for Mac 12.2.1中读取CSV文件。
他们的操作系统配置为使用“分号”;作为列表分隔符,这正是我在CSV中写的。他们还说,当他们在记事本中打开文件时,他们注意到没有换行符,所有内容都显示在一行中;这就是Excel无法正确读取文件的原因;但在我的代码中,我使用的是跨浏览器换行符\r\n
这是我使用的完整代码:
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=participantes.csv");
$separator = ";";
$rs = $sql->doquery("SELECT A QUERY TO RETRIEVE DATA FROM THE DB");
$header = "";
$num_fields = mysql_num_fields($rs);
for($i=0; $i<$num_fields; $i++){
$field = mysql_field_name($rs, $i);
$header .= $field.$separator;
}
echo $header."\r\n";
while($row = $sql->fetch($rs)){
$str = "";
for($i=0; $i<$num_fields; $i++){
$field = mysql_field_name($rs, $i);
$value = str_replace(";", ",", $row->{$field});
$value = str_replace("\n", ",", $value);
$value = str_replace("\d", ",", $value);
$value = str_replace(chr(13), ",", $value);
$str .= $value.$separator;
}
echo $str."\r\n";
}
我有什么办法可以让Mac用户正确阅读文件吗?
答案 0 :(得分:1)
出于调试目的:
答案 1 :(得分:0)
以下是我将标签分隔数据转换为CSV所做的一些代码,它在我的Mac上运行良好。请注意,我已将其设置为让我单击下载,而不是将其推送到浏览器。这不是一个很好的解决方案(我很确定代码是废话),但它适用于我需要它。
$input = $_POST['input'];
//Remove commas.
$replacedinput1 = str_replace(",", "-", $input);
//remove tabs, replace with commas
$replacedinput2 = str_replace(" ", ",", $replacedinput1);
//create an array
$explodedinput = explode("
", $replacedinput2);
//open the CSV file to write to; delete other text in it
$opencsvfile = fopen("/var/www/main/tools/replace_tab.csv","w+");
//for each line in the array, write it to the file
foreach($explodedinput as $line) {
fputcsv ($opencsvfile, split(',', $line));
};
//close the file
fclose($opencsvfile);
//have the user download the file.
/*
header('Pragma: public');
header('Expires: Fri, 01 Jan 2010 00:00:00 GMT');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/csv');
header('Content-Disposition: filename=replace_tab.csv'); */
//Or not, since I can't get it to work.
echo "<a href='replace_tab.csv'>Download CSV File, then open in Numbers or Excel (Note, you may need to right click, save as.)</a>.";
答案 2 :(得分:0)
Mac中的换行符是LF(unicode U + 000A),在Windows中是CR + LF(Unicode U + 000D后跟U + 000A)。
也许这就是为什么csv在Mac上无法读取的原因。