Importing a CSV

By Keith Connolly on July 23, 2011

Get Reading

CSV files are the life-blood of corporate america.  They are easy to use, easy to make, and easy to modify.  They import into almost every spreadsheet program ever made allowing them to be used by a varity of people.  When making webpages a common request is the ability for the end-user to be able to import a CSV file.  Recently I implemented a CSV import in a controller action on rails in order to allow users to bulk-create mobile sites on GoMobile the mobile web marketing platform where I lead development and technology. The following example allows a user to upload a file to the rails app, the app will parse the CSV create the records then disgard the temporary file.  This method works on heroku or servers where you have no write access to the file system.

In pages_controller add:

require 'csv'
...
	def csv_import
		row_count = 0
		@parsed_file=CSV::Reader.parse(params[:dump][:file])
 		@parsed_file.each do |row|
			col = 2
			#Generate a new page with the first and second column...
			pa = Page.new(
					:created_by => current_user.id,
					:page_title => row[0],
					:permalink => row[1]
			)
			pa.save
		end
		flash[:notice] = "Import was successful."
		redirect_to pages_path
	end

That action will loop through the whole csv file.  But how do you get the uploaded file to rails? In your view add:

 


<% form_for :dump, :url=>{
	:controller=>"pages",
	:action=>"csv_import"},
        :html => { :multipart => true } do |f| %>
        CSV:
        <%= f.file_field :file %>
        <%= submit_tag 'Import' %>
<% end %>
That's it! Well, of course you'll need to setup your routes a simple match /import to pages#csv_import will work. You can get amazingly complex with CSV imports -- I've even written a controller to handle all imports and had XLS, CSV, TSV, and XML which import to a model based on the files headers but that's for another time. I hope this helps and you enjoy it!

 

Get in touch

I really like hearing from those who read my content, engauge with me via the comments on each post are by one of the many contact methods below.


Keith Connolly
Queen Creek, Arizona 85142
P: (480) 231-9285