Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape semicolon character when writing to csv file

Tags:

I want to write something like

=HYPERLINK("http://example.com"; "Example") 

to a comma-separated CSV file, but Excel parses the semicolon and puts "Example") part in another cell. I tried escaping the semicolon with backslash and wrapping everything in double quotes without any luck.

Any help?

like image 914
donk Avatar asked Dec 14 '11 08:12

donk


People also ask

How do I escape a semicolon in a CSV file?

Actually, the only value to escape is double quotes symbol. All other cell content gets into it and displayed correctly in Excel. Checked with various versions of Excel and ODBC CSV parsers in Cyrillic locale under Windows.

Why is my CSV saving with semicolon?

In North America and some other countries, the default list separator is a comma, so you get CSV comma delimited. In European countries, a comma is reserved for the decimal symbol, and the list separator is generally set to semicolon. That is why the result is CSV semicolon delimited.

How do I escape a separator in CSV?

By default, the escape character is a " (double quote) for CSV-formatted files. If you want to use a different escape character, use the ESCAPE clause of COPY , CREATE EXTERNAL TABLE or gpload to declare a different escape character.


2 Answers

The wrapping with double quotes was already the correct idea, but you have to make sure you do it correctly. You can put a column within double quotes, then everything inside is considered as a single value. Quotes itself have to be escaped by writing two of them ("").

See for example this:

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 
like image 120
poke Avatar answered Sep 21 '22 17:09

poke


I also had a very wild time tring to figure the whole picture out, then is how I've got all my csv ready to open into excel in php ( which includes utf8 encoding as well ) :

$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); 
like image 32
Jack Avatar answered Sep 21 '22 17:09

Jack