时,我想写点东西像转义分号写入csv文件
=HYPERLINK("http://example.com"; "Example")
以逗号分隔的CSV文件,但Excel分析分号,并提出“实例”)的一部分在另一个单元格。我试着用反斜杠将分号转义出来,并用双引号将所有内容都包起来,没有任何运气。
任何帮助?
时,我想写点东西像转义分号写入csv文件
=HYPERLINK("http://example.com"; "Example")
以逗号分隔的CSV文件,但Excel分析分号,并提出“实例”)的一部分在另一个单元格。我试着用反斜杠将分号转义出来,并用双引号将所有内容都包起来,没有任何运气。
任何帮助?
用双引号包装已经是正确的想法,但你必须确保你做到了正确。您可以在双引号内放置一列,然后将所有内部视为单个值。行情本身必须通过编写其中两个(""
)来逃脱。
例如见这样的:
Column A;Column B;Column C
Column A;"Column B; with semicolon";Column C
Column A;"Column B"";"" with semicolon and quotes";Column C
Column A;"=HYPERLINK(""http://example.com""; ""Example"")";Column C
我也有一个很百搭的时间特林图的全貌了,那就是如何我有我的所有CSV准备在PHP开到Excel(这包括utf8编码):
$sep='";"';//note the separator is double quoted
while($t=mysql_fetch_assoc(mysql_query('select ..')){
#replaces the caracters who are breaking csv display
$t=array_map(function($x){return str_replace(array("\n","\r",'"'),array('\\n',"\\r",'""'),$x);},$t);
$csv.="\n\"".implode($sep,$t)."\"";
}
$charset='utf-8';
header('Content-Type: application/csv;charset='.$charset);
header('Content-Disposition: attachment; filename="filename.csv"');
$bom=chr(239).chr(187).chr(191);#this tells excel document is utf8 encoded
die($bom.$csv);
我使用此函数为每个CSV值传递正确。它仅在包含新行符号,双引号或分隔符时引用值。其实,逃脱的唯一价值是双引号符号。所有其他单元格内容都会进入并在Excel中正确显示。
在Windows下用Cyrillic语言环境检查各种版本的Excel和ODBC CSV解析器。
/**
* This function escapes single CSV value if it contains new line symbols, quotes or separator symbol and encodes it into specified $encoding.
*
* @param string $source - origin string
* @param string $sep - CSV separator
* @param string $source_encoding - origin string encoding
* @param string $encoding - destination encoding
*
* @return string - escaped string, ready to be added to CSV
*
* @example echo escapeStringCSV("Hello\r\n\"World\"!");
* will output
* "Hello
* ""World""!"
*/
function escapeStringCSV($source, $sep=';', $source_encoding='utf-8', $encoding="windows-1251//TRANSLIT"){
$str = ($source_encoding!=$encoding ? iconv($source_encoding, $encoding, $source) : $source);
if(preg_match('/[\r\n"'.preg_quote($sep, '/').']/', $str)){
return '"'.str_replace('"', '""', $str).'"';
} else
return $str;
}
所以使用可以是这样的:
while($row = mysql_fetch_assoc($res)){
foreach($row as $val){
$csv .= escapeStringCSV($val).';';
}
$csv .= "\r\n";
}