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

.open(file_name_or_io, _ = nil) ⇒ Object

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



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/io_streams/xlsx/reader.rb', line 7

def self.open(file_name_or_io, _ = nil)
  if file_name_or_io.is_a?(String)
    file_name = file_name_or_io
  else
    temp_file = Tempfile.new('iostreams_xlsx')
    temp_file.binmode
    IOStreams.copy(file_name_or_io, temp_file)
    file_name = temp_file.to_path
  end

  csv_temp_file = Tempfile.new('iostreams_csv')
  csv_temp_file.binmode
  new(file_name).each { |lines| csv_temp_file << lines.to_csv }
  csv_temp_file.rewind
  yield csv_temp_file
ensure
  temp_file.delete if temp_file
  csv_temp_file.delete if csv_temp_file
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