0

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.

dogg
  • 127
  • 1
  • 8

1 Answers1

1

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.

Luc
  • 143
  • 6
  • Thanks for your help! When I do this I get the following error "string contains null byte", when I look on google many answers says it about a bug with rails 4.0.2 but I don't think it must be the case, any idea where this comes from? – dogg May 20 '15 at 16:01
  • @dogg You probably have null bytes (zeros) in your input file. You should remove them (see http://stackoverflow.com/questions/11910040/exec-string-contains-null-byte-argumenterror). – Luc May 21 '15 at 10:02