Skip to content

Instantly share code, notes, and snippets.

@gmgent
Created April 23, 2011 06:47
Show Gist options
  • Save gmgent/938421 to your computer and use it in GitHub Desktop.
Save gmgent/938421 to your computer and use it in GitHub Desktop.
spreadsheet_row_enumerator.rb
class SpreadsheetRowEnumerator
include Enumerable
def initialize(file_name, sheet_name, starting_row = 2)
parsing_class = case File.extname(file_name)
when ".xls": Excel
when ".xlsm", ".xlsx": ExcelxNokogiri
end
@starting_row = starting_row
@worksheet = parsing_class.new(file_name)
@worksheet.default_sheet = sheet_name
end
def each
@starting_row.upto(@worksheet.last_row) do |i|
yield row(i)
end
end
def row(row_number)
row_to_attribute_hash(@worksheet.row(row_number))
end
protected
def header_columns
@worksheet.row(1).map { |header| header.try(:strip).try(:downcase) }
end
def row_to_attribute_hash(row)
Hash[*header_columns.zip(row).flatten]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment