class SimpleExcel::Worksheet

Attributes

excel[R]

@attr_reader [Object] excel Instance of Spreadsheet::Excel::Workbook @attr_reader [Array] headers Headers excel file @attr_reader [Object] sheet Instance of Spreadsheet::Excel::Worksheet

headers[R]

@attr_reader [Object] excel Instance of Spreadsheet::Excel::Workbook @attr_reader [Array] headers Headers excel file @attr_reader [Object] sheet Instance of Spreadsheet::Excel::Worksheet

sheet[R]

@attr_reader [Object] excel Instance of Spreadsheet::Excel::Workbook @attr_reader [Array] headers Headers excel file @attr_reader [Object] sheet Instance of Spreadsheet::Excel::Worksheet

Public Class Methods

new(excel, headers, check_headers = true) click to toggle source

Create new instance of SimpleExcel::Worksheet

@param [Object] excel Instance of Spreadsheet @param [Array] headers Headers excel file @param [Boolean] check_headers Check headers

@return [Object] Instance of SimpleExcel::Worksheet

# File lib/simple-excel/worksheet.rb, line 17
def initialize(excel, headers, check_headers = true)
  @excel, @headers = excel, headers

  if check_headers
    @excel.worksheets.each_with_index do |sheet, index|
      @sheet = @excel.worksheet(index)
      return @sheet if @headers == sheet.row(0)
    end
    raise HeadersDoNotMatch, "File headers do not coincide with #{@headers}"
  else
    @sheet = @excel.worksheet(0)
  end
end

Public Instance Methods

each() { |row| ... } click to toggle source

Pass all rows excel file

@yield [row] Row excel file @yieldparam [Hash] Hash of values with headers

# File lib/simple-excel/worksheet.rb, line 40
def each
  raise FileWithoutData, 'File contains no data' if no_data?
  (1..@sheet.last_row_index).each do |i|
    row = get_values(i)
    yield row
  end
end
to_s() click to toggle source

@return [String] Class name

# File lib/simple-excel/worksheet.rb, line 32
def to_s
  self.class
end

Private Instance Methods

get_values(index) click to toggle source

Get data from the row

@param [Fixnum] index Index of row @return [Hash] Hash of values with headers

# File lib/simple-excel/worksheet.rb, line 61
def get_values(index)
  active_row = @sheet.row(index)
  headers_with_values = []
  @headers.each_with_index { |header, index| headers_with_values << [header, active_row[index]] }
  headers_with_values << ['index', index]
  Hash[*headers_with_values.flatten]
end
no_data?() click to toggle source

Check data without headers

@return [Boolean] True if no data or false

# File lib/simple-excel/worksheet.rb, line 53
def no_data?
  @sheet.last_row_index == 0
end