Generating fields containing newline with Ruby CSV::Writer

六眼飞鱼酱① 提交于 2020-01-14 12:44:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!