Class: IOStreams::Xlsx::Reader

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_name) ⇒ Reader

Returns a new instance of Reader.



27
28
29
30
31
32
33
34
35
36
# File 'lib/io_streams/xlsx/reader.rb', line 27

def initialize(file_name)
  begin
    require 'creek' unless defined?(Creek::Book)
  rescue LoadError => e
    raise(LoadError, "Please install the 'creek' gem for xlsx streaming support. #{e.message}")
  end

  workbook   = Creek::Book.new(file_name, check_file_extension: false)
  @worksheet = workbook.sheets[0]
end

Class Method Details

.extract_csv(file_name, &block) ⇒ Object

Convert the spreadsheet to csv in a tempfile



18
19
20
21
22
23
24
25
# File 'lib/io_streams/xlsx/reader.rb', line 18

def self.extract_csv(file_name, &block)
  IOStreams::File::Path.temp_file_name('iostreams_csv') do |temp_file_name|
    IOStreams::File::Writer.open(temp_file_name) do |io|
      new(file_name).each { |lines| io << lines.to_csv }
    end
    IOStreams::File::Reader.open(temp_file_name, &block)
  end
end

.open(file_name_or_io, _ = nil, &block) ⇒ Object

Convert a xlsx, or xlsm file or stream into CSV format.



7
8
9
10
11
12
13
14
15
# File 'lib/io_streams/xlsx/reader.rb', line 7

def self.open(file_name_or_io, _ = nil, &block)
  return extract_csv(file_name_or_io, &block) if file_name_or_io.is_a?(String)

  # Creek gem can only work against a file, not a stream, so create temp file.
  IOStreams::File::Path.temp_file_name('iostreams_xlsx') do |temp_file_name|
    IOStreams.copy(file_name_or_io, temp_file_name, target_options: {streams: []})
    extract_csv(temp_file_name, &block)
  end
end

Instance Method Details

#eachObject

Returns each [Array] row from the spreadsheet



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

def each
  @worksheet.rows.each { |row| yield row.values }
end