Class: ReadXls::Spreadsheet

Inherits:
Object
  • Object
show all
Defined in:
lib/read_xls/spreadsheet.rb

Constant Summary collapse

ParsingFailedError =
Class.new(StandardError)
BYTE_LENGTH =
2

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ole) ⇒ Spreadsheet

Returns a new instance of Spreadsheet.



14
15
16
17
18
19
20
# File 'lib/read_xls/spreadsheet.rb', line 14

def initialize(ole)
  self.position = 0
  self.biff     = ole.file.read("Workbook")
  self.workbook = parse_workbook
ensure
  ole.close
end

Instance Attribute Details

#biffObject

Returns the value of attribute biff.



6
7
8
# File 'lib/read_xls/spreadsheet.rb', line 6

def biff
  @biff
end

#positionObject

Returns the value of attribute position.



6
7
8
# File 'lib/read_xls/spreadsheet.rb', line 6

def position
  @position
end

#workbookObject

Returns the value of attribute workbook.



6
7
8
# File 'lib/read_xls/spreadsheet.rb', line 6

def workbook
  @workbook
end

Class Method Details

.parse(xls_file_path) ⇒ Object



8
9
10
11
12
# File 'lib/read_xls/spreadsheet.rb', line 8

def self.parse(xls_file_path)
  new(
    Ole::Storage.open(xls_file_path, "rb+")
  )
end

Instance Method Details

#parse_workbookObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/read_xls/spreadsheet.rb', line 26

def parse_workbook
  workbook_builder = WorkbookBuilder.new(biff)

  loop do
    record_number = read_byte
    break if record_number == ::ReadXls::RecordHandler::EOF

    record_length = read_byte
    record_data   = read_data(record_length)

    ::ReadXls::RecordHandler.call(
      record_number,
      workbook_builder,
      biff,
      record_data
    )
  end

  workbook_builder.build
end

#read_byteObject



54
55
56
57
58
# File 'lib/read_xls/spreadsheet.rb', line 54

def read_byte
  val           = biff[position, BYTE_LENGTH].unpack("v")
  self.position += BYTE_LENGTH
  val.first || raise(ParsingFailedError, "expected to get value, got nil")
end

#read_data(bytes) ⇒ Object



47
48
49
50
51
# File 'lib/read_xls/spreadsheet.rb', line 47

def read_data(bytes)
  val           = biff[position, bytes]
  self.position += bytes
  val
end

#sheetsObject



22
23
24
# File 'lib/read_xls/spreadsheet.rb', line 22

def sheets
  workbook.worksheets
end