7

I'm trying to export the following string

"sep = ,"

to a CSV-file, as to be able to define the separation symbol.

However, when using the following command:

Export["test.csv", Join[{"sep = ,"}, RandomInteger[{-5, 5}, {5, 3}]], "CSV"]

I get the quotes around the string in the first line:

"sep = ,"
-4,5,0
5,-4,-1
0,5,2
-1,2,4
-1,-4,-1

This obviously isn't recognized by Excel and it doesn't open correctly. I've tried changing the string to something like

Style["sep=,", ShowStringCharacters -> False]

and then export again, but then I just get this whole command into the CSV-file.

Is there a method to export this string without the quotes attached to them into a CSV-file?

VividD
  • 3,660
  • 4
  • 26
  • 42
Gabriel
  • 1,877
  • 12
  • 22
  • AFAIK, strings can only be exported without the quotation marks if done via streams, as in stream=OpenWrite[file];WriteString[stream, "string..."];Close@stream or if OpenWrite is called with the option FormatType -> OutputForm, but that might cause unwanted formatting on other characters. – István Zachar Jan 24 '14 at 18:19
  • 2
    Of curiosity is there some software that actually needs that header? Undoubtedly it will break many things (eg Mathematica will just include it as a data line if you import..) – george2079 Jan 24 '14 at 18:52
  • Actually, this is standard behavior for Excel exports to CSV too. If a string contains a field separator (a comma in this case) it needs to be quoted otherwise it will be seen (incorrectly) as a field separator upon import. Excel will automatically quote the string – Sjoerd C. de Vries Apr 27 '14 at 19:54

2 Answers2

13
 Export["test.csv", Join[{"sep = ,"}, 
        RandomInteger[{-5, 5}, {5, 3}]], "TextDelimiters"->None]

(With the obvious issue if you also have strings that should be quoted in the data )

george2079
  • 38,913
  • 1
  • 43
  • 110
5

If I try to create a CSV file without the first line indicating the seperator, the resulting file is readable by Excel.

 Export["test2.csv",RandomInteger[{-5,5},{5,3}]]

But if you still want the first line, I would do something like this

Export["test3.csv", 
 "sep = ,\n" <> ExportString[RandomInteger[{-5, 5}, {5, 3}], "CSV"]
 , "Text"]
Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • 1
    Sadly, with my language settings, Excel wants ";" as delimiters. I've tried to change that, but that wasn't successful. Thanks for the good help! – Gabriel Jan 24 '14 at 18:41
  • 3
    Ahh, okay. Another solution would be to export it as a "Table" but usint the FieldSparators option. Like Export["test.csv",RandomInteger[{-5,5},{5,3}],"Table","FieldSeparators"->" ; "] – Jason B. Jan 24 '14 at 18:58
  • 1
    Another approach might be to export comma separated, but with a "txt" extension. I think then Excel will pop up a box and let you tell it what the delimiter is. – george2079 Jan 24 '14 at 20:13