我想写点类似的东西
=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下的西里尔语言环境中的各种版本的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"; }
3 回答
双引号包装已经是正确的想法,但你必须确保你正确地做到了 . 您可以将列放在双引号内,然后将内部的所有内容视为单个值 . 引用本身必须通过写两个(
""
)来逃避 .参见例如:
我还有一个非常狂野的时间来弄清楚整个画面,然后我是如何让我的所有csv准备好在php中打开excel(其中包括utf8编码):
我为每个CSV值使用此函数来正确传递它 . 仅在包含新行符号,双引号或分隔符时才引用值 . 实际上,唯一要逃避的值是双引号符号 . 所有其他单元格内容都会进入并在Excel中正确显示 .
使用Windows下的西里尔语言环境中的各种版本的Excel和ODBC CSV解析器进行检查 .
所以用法可以是这样的: