在 Rails 中使用 smarter_csv 引用列号 5
Reference column number using smarter_csv in Rails 5
我目前正在使用 smarter_csv gem 将数据从 CSV 导入我的 Rails 应用程序。理想情况下,我想访问按数字而不是 header 名称导入的列,因为 header 名称可能与传入的数据有些不一致。
有人成功过吗?类似下面的代码就完美了。
SmarterCSV.process(file,
col_sep: ',',
force_simple_split: false,
downcase_header: false,
row_sep: :auto) do |row|
row[1] #get data from whatever column number here
end
该行作为散列返回,但我认为我不能指望散列的顺序是一致的。
提前致谢!
我还没有测试过,但也许可以试试 Custom Header Transformations via Procs
change_headers_to_position = Proc.new {|headers|
headers.each_with_index.map{|h, index| index + 1 }
}
options = {
header_transformations: [:none, change_headers_to_position ]
}
data = SmarterCSV.process('/tmp/test.csv', options)
我目前正在使用 smarter_csv gem 将数据从 CSV 导入我的 Rails 应用程序。理想情况下,我想访问按数字而不是 header 名称导入的列,因为 header 名称可能与传入的数据有些不一致。
有人成功过吗?类似下面的代码就完美了。
SmarterCSV.process(file,
col_sep: ',',
force_simple_split: false,
downcase_header: false,
row_sep: :auto) do |row|
row[1] #get data from whatever column number here
end
该行作为散列返回,但我认为我不能指望散列的顺序是一致的。 提前致谢!
我还没有测试过,但也许可以试试 Custom Header Transformations via Procs
change_headers_to_position = Proc.new {|headers|
headers.each_with_index.map{|h, index| index + 1 }
}
options = {
header_transformations: [:none, change_headers_to_position ]
}
data = SmarterCSV.process('/tmp/test.csv', options)