How to map data imported via xlsx with no headers in rails 4

312 Views Asked by At

I want to add an import function for the users of my rails app, however the files that they will import won't have a header and the interesting data will start at row 8. In the rows I only need 2 fields Here is an example of a line in the xlsx file :

751,"01/17/2015","11:17:32","60","TDFSRDSK","2","10","-1","0","3","","26","3","","","1","0"  

I'll only need the date and the number in 4th field (60) and add them to an SQL table I have a problem with the mapping and how to do it. I've tried to do it based on the railscast tutorial and roo doc but I can't manage to make it work.

def self.import(file)
 xlsx = Roo::Excelx.new(file)
 xlsx.each_row do |row|
  date = row[2]
  value = row[4]
  user_id = current_user.id
  product.create(:date => date, :valeur => value, :user_id => user_id)
 end
end

And the error I get :

no implicit conversion of ActionDispatch::Http::UploadedFile into String

I'm really new to rails/ruby so I'm not even sure the mapping code is supposed to be like that.

1

There are 1 best solutions below

2
On

It seems like you need to read the contents of the uploaded file into a String object first:

xlsx = Roo::Excelx.new(file.read)

You can refer to the relevant Rails guide for details on how this works.