Class: IOStreams::Xlsx::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/io_streams/xlsx/reader.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(workbook) ⇒ Reader

Returns a new instance of Reader.



39
40
41
# File 'lib/io_streams/xlsx/reader.rb', line 39

def initialize(workbook)
  @worksheet = workbook.sheets[0]
end

Instance Attribute Details

#worksheetObject (readonly)

Returns the value of attribute worksheet.



6
7
8
# File 'lib/io_streams/xlsx/reader.rb', line 6

def worksheet
  @worksheet
end

Class Method Details

.open(file_name_or_io, buffer_size: 65536, &block) ⇒ Object

Read from a xlsx, or xlsm file or stream.

Example:

IOStreams::Xlsx::Reader.open('spreadsheet.xlsx') do |spreadsheet_stream|
  spreadsheet_stream.each_line do |line|
    puts line
  end
end


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/io_streams/xlsx/reader.rb', line 16

def self.open(file_name_or_io, buffer_size: 65536, &block)
  begin
    require 'creek' unless defined?(Creek::Book)
  rescue LoadError => e
    raise(LoadError, "Please install the 'creek' gem for xlsx streaming support. #{e.message}")
  end

  if IOStreams.reader_stream?(file_name_or_io)
    temp_file = Tempfile.new('rocket_job_xlsx')
    file_name = temp_file.to_path

    ::File.open(file_name, 'wb') do |file|
      IOStreams.copy(file_name_or_io, file, buffer_size)
    end
  else
    file_name = file_name_or_io
  end

  block.call(self.new(Creek::Book.new(file_name, check_file_extension: false)))
ensure
  temp_file.delete if temp_file
end

Instance Method Details

#each(&block) ⇒ Object Also known as: each_line

Returns each [Array] row from the spreadsheet



44
45
46
# File 'lib/io_streams/xlsx/reader.rb', line 44

def each(&block)
  worksheet.rows.each { |row| block.call(row.values) }
end