处理Ruby CSV中的多行单元格

时间:2014-10-14 11:53:37

标签: ruby csv newline

require 'csv'
input = CSV.read("test_first.csv", :encoding => 'ascii')[1 .. -1]
DOC = "test_final.csv"

profile = []

profile[0] = "Multiline"
profile[1] = "Standard"

CSV.open(DOC, mode = 'w', :force_quotes => true) do |me|
 me << profile
end


a = 0 
b = input.length 
while a < b 
 temp = []
 temp = input[a]
 profile = []

 profile[0] = ' A text string with embedded newlines
 as well as some substitution from the source file: '"#{temp[0]}"''
 profile[1] = temp[1]

 CSV.open(DOC, mode = "a", :force_quotes => true ) do |me|
    me << profile
  end
  a += 1
end

生成的文件test_final.csv在单元格中保留了所需的换行符,但force_quotes没有按预期工作,嵌入的换行符也没有被转义。因此,当在文本编辑器中检查test_final.csv时,它会有比预期更多的行,因为每个换行都被视为一个新行。

我尝试使用自己独特的行分隔符&gt;附加违规列。个人资料[0] =&#39;带有嵌入换行符的文本字符串      以及源文件中的一些替换:&#39;&#34;#{temp [0]}&#34;&#39;〜&#39;并在选项哈希中分配,如此&gt; :row_sep =&gt; &#34;〜&#34;但这似乎没有用。

关于所需输入和输出的一些说明

Desired Input:
test_first.csv
1.testHeader1,testheader2
2.sub1,standard1
3.sub2,standard2

Desired Output:
test_final.csv
1.Multiline,Standard
2. A text string with embedded newlines
     as well as some substitution from the source file: sub1,standard1
3. A text string with embedded newlines
     as well as some substitution from the source file: sub2,standard2

What I'm getting right now instead is:
test_fail.csv
1.Multiline,Standard
2. A text string with embedded newlines
3.    as well as some substitution from the source file: sub1,standard1
4. A text string with embedded newlines
5.    as well as some substitution from the source file: sub2,standard2

0 个答案:

没有答案