1

I have a file b.xls from excel I need to import it to my rails app

enter image description here

I have tried to open it

file = File.read(Rails.root.to_s+'/b.xls')

I have got thisenter image description here

file.encoding => #Encoding:UTF-8

I have few questions:

  1. how to open without this symbols(normal language)?

  2. how to convert this file to a hash?

    File pretty large about 5k lines

6

1 Answer 1

0

You must have array of all rows then you can convert it to some hash if you like so.

I would recommend to use a batch_factory gem.
The gem is very simple and relies on the roo gem under the hood.
Here is the code example

require 'batch_factory'
factory = BatchFactory.from_file(
  Rails.root.join('b.xlsx'),
  keys: [:column1, :column2, ..., :what_ever_column_name]
)

Then you can do

factory.each do |row|
  puts row[:column1]
end

You can also omit specifying keys. Then batch_factory will automatically fetch headers from the first row. But your keys would be in russian. Like

factory.each do |row|
  puts row['Товар']
end

If you want to hash with product name as key you can do

factory.inject({}) do |hash, row|
  hash.merge(row['Товар'] => row)
end
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.