问题
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?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/822240/generating-fields-containing-newline-with-ruby-csvwriter