简体   繁体   English

CSV.generate时,生成不带“”的空字段

[英]When CSV.generate, generate empty field without “”

Ruby 2.2, Ruby on Rails 4.2 Ruby 2.2、Ruby on Rails 4.2

I'm genarating some CSV data in Ruby on Rails, and want empty fields to be empty, like ,, not like ,"", .我正在 Ruby on Rails 中生成一些 CSV 数据,并希望空字段为空,例如,,而不是,"", I wrote codes like below:我写了如下代码:

somethings_cotroller.rb somethings_cotroller.rb

def get_data
  respond_to do |format|
    format.html
    format.csv do
      @data = SheetRepository.accounts_data
      send_data render_to_string, type: :csv
    end
  end
end

somethings/get_data.csv.ruby东西/get_data.csv.ruby

require 'csv'
csv_str = CSV.generate do |csv|
  csv << [1,260,37335,'','','','','','']
  ...
end

And this generates CSV file like this.这会生成这样的 CSV 文件。

get_data.csv获取数据.csv

1,260,37335,"","","","","",""

I want CSV data like below.我想要像下面这样的 CSV 数据。

1,260,37335,,,,,,

It seems like Ruby adds "" automatically.看起来Ruby会自动添加“”。

How can I do this??我该怎么做??

In order to get CSV to output an empty column, you need to tell it that nothing is in the column.为了让 CSV 输出一个空列,您需要告诉它该列中没有任何内容。 An empty string, in ruby, is still something, you'll need to replace those empty strings with nil in order to get the output you want:一个空字符串,在 ruby​​ 中,仍然是一些东西,你需要用nil替换这些空字符串以获得你想要的输出:

csv_str = CSV.generate do |csv|
  csv << [1,260,37335,'','','','','',''].map do |col|
    col.respond_to?(:empty?) && col.empty? ? nil : col
  end
end
# => 1,260,37335,,,,,,

In rails you can clean that up by making use of presence , though this will blank out false as well:在 rails 中,您可以通过使用presence来清理它,尽管这也会清除false

csv_str = CSV.generate do |csv|
  csv << [1,260,37335,'',false, nil,'','',''].map(&:presence)
end
# => 1,260,37335,,,,,,

The CSV documentation shows an option that you can use for this case. CSV 文档显示了可用于这种情况的选项。 There are not examples but you can guess what it does.没有例子,但你可以猜到它的作用。

The only consideration is, you need to send an array of Strings, otherwise, you will get a NoMethodError唯一的考虑是,你需要发送一个字符串数组,否则,你会得到一个NoMethodError

csv_str = CSV.generate(write_empty_value: nil) do |csv|
  csv << [1,260,37335,'','','','','','', false, ' ', nil].map(&:to_s)
end
=> "1,260,37335,,,,,,,false, ,\n"

The benefit of this solution is, you preserve the false .此解决方案的好处是,您可以保留false

I resolved by myself!我自己解决了!

in somethings_controller.rb在 somethings_controller.rb 中

send_data render_to_string.gsub("\"\"",""), type: :csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM