2010-05-12 48 views
9

我使用this tutorial中的代碼解析CSV文件並將其內容添加到數據庫表中。我將如何忽略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 

回答

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

order n extra comparison – baash05 2012-03-01 02:09:03

41

這個問題保持雨後春筍般冒出來時,我正在尋找如何跳過與CSV/FasterCSV圖書館的第一線,所以這裏是如果你最終的解決方案這裏。

解決的辦法是...... CSV.foreach("path/to/file.csv",{:headers=>:first_row}) do |row|

HTH。

+5

你也可以傳遞散列'{:headers => true}'作爲第二個參數。這也適用。 – 2012-04-27 09:52:45

3

如果您將第一行標識爲標題,則返回對象而不是簡單的Array

當您抓取單元格值時,您似乎需要在對象上使用.fetch("Row Title")

這就是我想出來的。我正在使用我的if條件跳過nil

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

0
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 
0
data_rows_only = csv.drop(1) 

會做

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

將循環它

0

使用這個簡單的代碼,你可以讀一個CSV文件,而忽略了第一線,是頭部或字段名稱:

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

你可以做你想做什麼都與row。別忘了headers: true