Class: ReadXls::Spreadsheet

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

Constant Summary collapse

ParsingFailedError =
Class.new(StandardError)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ole) ⇒ Spreadsheet

Returns a new instance of Spreadsheet.



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

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.



3
4
5
# File 'lib/read_xls/spreadsheet.rb', line 3

def biff
  @biff
end

#positionObject

Returns the value of attribute position.



3
4
5
# File 'lib/read_xls/spreadsheet.rb', line 3

def position
  @position
end

#workbookObject

Returns the value of attribute workbook.



3
4
5
# File 'lib/read_xls/spreadsheet.rb', line 3

def workbook
  @workbook
end

Class Method Details

.parse(xls_file_path) ⇒ Object



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

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

Instance Method Details

#parse_workbookObject



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

def parse_workbook
  workbook_builder = WorkbookBuilder.new(biff)

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

    record_length = read_word
    record_data   = read_data(record_length)

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

  workbook_builder.build
end

#read_data(bytes) ⇒ Object



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

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

#read_wordObject



52
53
54
55
56
# File 'lib/read_xls/spreadsheet.rb', line 52

def read_word
  val           = biff.byteslice(position, 2).unpack("v")
  self.position += 2
  val.first || raise(ParsingFailedError, "expected to get value, got nil")
end

#sheetsObject



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

def sheets
  workbook.worksheets
end