Skip to content

Instantly share code, notes, and snippets.

@gmgent
Created April 23, 2011 06:47

Revisions

  1. Krister Axel created this gist Apr 23, 2011.
    34 changes: 34 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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