Pages

Wednesday 9 April 2014

CSV Import using inbuilt library (CSV)


Importing a CSV from your local system

  • For importing the csv file from local file system, In your controller write require 'csv' at the top or in the action to include these classes.
  • And if you are importing a csv file from the server, then you have to write require 'csv' and
    require 'open-uri' in your controller.
  • Suppose you have saved the csv as-

    user_info.csv and open this file into texteditor
  • Then in your action write the code as follows:-

      csv_array_file = Array.new
      CSV.new(open('/tmp/user_info.csv'), :col_sep => ',').each do |row|
        csv_array_file << row
      end

  • You can also import the csv directly into the db as follows:-
CSV.new(open(<local file path or remote file path>), :col_sep => <column seprator>).each do |row|
record = active_record_class.new(:attr1 => row[0], :attr2 => row[1])
record.save!

  • end


        No comments:

        Post a Comment