views:

573

answers:

2

I want to make CSV::Writer generate a line break within a quoted string:

A,B,"Line
Line",C

So that the row would display in Excel as:

A,B,Line,C
    Line

Is it possible to prevent CSV:Writer from stripping out newlines? If not, would switching to FasterCSV solve this problem?

+2  A: 

Switching to FasterCSV will work.

From an IRB session:

  require 'fastercsv'
  FasterCSV.open("./testfile.csv", "w") do |csv|
    csv << ["row", "of", "CSV\nCSV", "data"]
  end
Jonathan R. Wallace
A: 

Looks like you can if you set the row separator to something other than the default (which is \r\n or \n). Here's an example (have a look at the last parameter specified in the call to CSV.parse_row):

require 'csv'

src = "a,test\ntest,b\ra,test\ntest,b,c"
idx = 0
begin
  parsed = []
  parsed_cells, idx = CSV.parse_row(src, idx, parsed, ',', ?\r)
  puts "Parsed #{ parsed_cells } cells."
  p parsed
end while parsed_cells > 0

Here is the output:

Parsed 3 cells.
["a", "test\ntest", "b"]
Parsed 4 cells.
["a", "test\ntest", "b", "c"]

Hope this helps.

Eric