4

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?

Ray Myers
  • 533
  • 5
  • 14

2 Answers2

2

The current CSV module supports newline characters in individual cells.

From an IRB session:

  require 'csv'
  CSV.open("./testfile.csv", "w") do |csv|
    csv << ["row", "of", "CSV\nCSV", "data"]
  end

Switching to FasterCSV will also work. From another IRB session:

require 'fastercsv'
FasterCSV.open("./testfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV\nCSV", "data"]
end
fresskoma
  • 25,481
  • 10
  • 85
  • 128
1

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
  • 757
  • 5
  • 11
  • The OP's question is not clear, but I was under the impression the requested conversion was "in-memory array of rows" --> output file and not the opposite. So the OP is trying to write a CSV file from in-memory fields that contain line breaks. – Cyril Duchon-Doris Apr 16 '18 at 17:42