忽略csv解析Rails的第一行

时间:2010-05-12 12:20:57

标签: ruby-on-rails csv

我正在使用this tutorial中的代码来解析CSV文件并将内容添加到数据库表中。我如何忽略CSV文件的第一行?控制器代码如下:

def csv_import 
  @parsed_file=CSV::Reader.parse(params[:dump][:file])
  n = 0
  @parsed_file.each  do |row|
    s = Student.new
    s.name = row[0]
    s.cid = row[1]
    s.year_id = find_year_id_from_year_title(row[2])
    if s.save
      n = n+1
      GC.start if n%50==0
    end
    flash.now[:message] = "CSV Import Successful, #{n} new students added to the database."
  end
  redirect_to(students_url)
end

6 个答案:

答案 0 :(得分:42)

当我在搜索如何跳过CSV / FasterCSV库的第一行时,这个问题不断出现,所以这里的解决方案 ,如果你最终在这里。

解决方案是...... CSV.foreach("path/to/file.csv",{:headers=>:first_row}) do |row|

HTH。

答案 1 :(得分:14)

@parsed_file.each_with_index  do |row, i|
  next if i == 0
  ....

答案 2 :(得分:4)

如果您将第一行标识为标题,则会返回Row个对象,而不是简单的Array

当您获取单元格值时,您似乎需要在.fetch("Row Title")对象上使用Row

这就是我想出的。我使用nil条件跳过if

CSV.foreach("GitHubUsersToAdd.csv",{:headers=>:first_row}) do |row| username = row.fetch("GitHub Username") if username puts username.inspect end end

答案 3 :(得分:1)

require 'csv'
csv_content =<<EOF
lesson_id,user_id
5,3
69,95
EOF

parse_1 = CSV.parse csv_content
parse_1.size # => 3  # it treats all lines as equal data

parse_2 = CSV.parse csv_content, headers:true
parse_2.size # => 2  # it ignores the first line as it's header

parse_1
# => [["lesson_id", "user_id"], ["5", "3"], ["69", "95"]]     
parse_2
# => #<CSV::Table mode:col_or_row row_count:3> 

这里是有趣的部分

parse_1.each do |line|
  puts line.inspect        # the object is array
end
# ["lesson_id", "user_id"]
# ["5", " 3"]
# ["69", " 95"]


parse_2.each do |line|
  puts line.inspect        # the object is `CSV::Row` objects
end
# #<CSV::Row "lesson_id":"5" "user_id":" 3">
# #<CSV::Row "lesson_id":"69" "user_id":" 95">

因此我可以做到

parse_2.each do |line|
  puts "I'm processing Lesson #{line['lesson_id']} the User #{line['user_id']}"
end
# I'm processing Lesson 5 the User 3
# I'm processing Lesson 69 the User 95

答案 4 :(得分:1)

data_rows_only = csv.drop(1)

会这样做

csv.drop(1).each do |row|
  # ...
end

将循环播放

答案 5 :(得分:1)

使用这个简单的代码,您可以读取CSV文件并忽略第一行,即标题或字段名称:

CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row|
    puts row.inspect
end

您可以使用row执行任何操作。别忘了headers: true

相关问题