Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore first line on csv parse Rails

I am using the code from this tutorial to parse a CSV file and add the contents to a database table. How would I ignore the first line of the CSV file? The controller code is below:

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
like image 850
Jack Avatar asked May 12 '10 12:05

Jack


4 Answers

Using this simple code, you can read a CSV file and ignore the first line which is the header or field names:

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

You can do what ever you want with row. Don't forget headers: true

like image 104
Aboozar Rajabi Avatar answered Sep 21 '22 18:09

Aboozar Rajabi


This question kept popping up when i was searching for how to skip the first line with the CSV / FasterCSV libraries, so here's the solution that if you end up here.

the solution is... CSV.foreach("path/to/file.csv",{:headers=>:first_row}) do |row|

HTH.

like image 46
afxjzs Avatar answered Nov 11 '22 23:11

afxjzs


@parsed_file.each_with_index  do |row, i|
  next if i == 0
  ....
like image 13
Maxem Avatar answered Nov 11 '22 23:11

Maxem


If you identify your first line as headers then you get back a Row object instead of a simple Array.

When you grab cell values, it seems like you need to use .fetch("Row Title") on the Row object.

This is what I came up with. I'm skipping nil with my if conditional.

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

like image 4
Alex Levine Avatar answered Nov 11 '22 23:11

Alex Levine