Creating fields containing newline with Ruby CSV :: Writer

I want CSV :: Writer to generate a line break on the quoted line:

A,B,"Line
Line",C 

      

To make the string appear in Excel as:

A,B,Line,C
    Line

      

Is it possible to prevent CSV: Writer from deleting newlines? If not, will FasterCSV switch to this problem?

+4


source to share


2 answers


Switching to FasterCSV will work.

From the IRB session:



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

      

+2


source


It looks like you can set the line separator to a value other than the default (which is \ r \ n or \ n). Here's an example (look at the last parameter in the CSV.parse_row call):

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's the result:



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

      

Hope it helps.

+1


source







All Articles