Home » excel » ruby on rails – How to open xls files with roo

ruby on rails – How to open xls files with roo

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have an “.xls” file, and I have to open it with roo, and it have to be opened with rake.

This is my rake file:

require 'roo'
namespace :exel do 

  task open: :environment do

    workbook = Roo::Excel.new("lib/tasks/users.xls") 
    password_length = 6
    password = Devise.friendly_token.first(password_length)
    p password
    username = "#{workbook.row(5)[0]}#{workbook.row(5)[1]}".slice!(0..7).downcase
    p username
    test_user = User.create!(email: '[email protected]', 
                 f_name: workbook.row(5)[0], 
                 l_name: workbook.row(5)[1],
                 username: username,
                 validity_date: workbook.row(5)[3],
                 :password => password, 
                 :password_confirmation => password)
    p test_user
  end
end

And when I run rake:exel, I get an Ole::Storage::FormatError: OLE2 signature is invalid error. From roo gem site I know that roo need roo-xls gem, I set it on my gemfile run bundle install, and it didn`t help 🙁

When I change format to xlsx it works good, but I have to open it as .xls, my thought is that I`am not importing roo-xls gem correctly.

Any help, idea will be very helpful.

How to&Answers:

I cam with solution 🙂
to change:

workbook = Roo::Excel.new("lib/tasks/users.xls")

to:

workbook = Roo::Spreadsheet.open("lib/tasks/users.xls", extension: :xlsx) 

this way I don`t have to change the file, as it will be opened as xlsx, file which will suite me, on the other side, code like:

workbook = Roo::Excelx.new("lib/tasks/users.xls", extension: :xlsx) 

returns an error: TypeError: lib/tasks/users.xls is not an Excel 2007 file