roo-rb / roo

Roo provides an interface to spreadsheets of several sorts.
MIT License
2.78k stars 503 forks source link

Better way to generate hashes instead of arrays #531

Open Kutomore opened 4 years ago

Kutomore commented 4 years ago

Issue

I have a multisheet xlsx file in which the pagename is a class name, and every row name matches an attribute on my database.

I want to do something like

speadsheet = Roo::Spreadsheet.open(params[:file].path, extension: :xlsx)
speadsheet.each_with_pagename  do |name, sheet|
  sheet.each { |row| name.constantize.create(row) }
end

Which would require me to have the row as a hash instead of an array.

The documentation suggests:

sheet.each(id: 'ID', name: 'FULL_NAME') do |hash|
  puts hash.inspect
  # => { id: 1, name: 'John Smith' }
end

But having to specify the attributes for each model would make the code very repetitive and ugly, is there a way for me to let the gem know that, for example the id column will match the id attribute?

Hampei commented 3 years ago

sheet.each(headers: :first_row) is what you want, but sadly yields the header row at the moment, so you'll have to skip that.

sheet.parse(headers: :first_row).each works correctly, but will cost you a bit more memory.