How should I escape commas and speech marks in CSV files so they work in Excel?

centralscru picture centralscru · Sep 18, 2012 · Viewed 99.5k times · Source

I'm generating a CSV file (delimited by commas rather than tabs). My users will most likely open the CSV file in Excel by double clicking it. My data may contain commas and speech marks, so I'm escaping those as follows.

Reference, Title, Description
1, "My little title", "My description, which may contain ""speech marks"" and commas."
2, "My other little title", "My other description, which may also contain ""speech marks"" and commas."

As far as I know that's always been the way to do it. Here's my boggle: when I open this file in Excel 2010 my escaping is not respected. Speech marks appear on the sheet, and the comma causes new columns.

Answer

centralscru picture centralscru · Sep 18, 2012

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!