Class: WrapExcel::Book

Inherits:
Object
  • Object
show all
Defined in:
lib/wrap_excel/book.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, options = { }, &block) ⇒ Book

Returns a new instance of Book.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/wrap_excel/book.rb', line 7

def initialize(file, options={ }, &block)
  @options = {
    :read_only => true,
    :displayalerts => false,
    :visible => false
  }.merge(options)
  file = WrapExcel::Cygwin.cygpath('-w', file) if RUBY_PLATFORM =~ /cygwin/
  file = WIN32OLE.new('Scripting.FileSystemObject').GetAbsolutePathName(file)
  @winapp = WIN32OLE.new('Excel.Application')
  @winapp.DisplayAlerts = @options[:displayalerts]
  @winapp.Visible = @options[:visible]
  WIN32OLE.const_load(@winapp, WrapExcel) unless WrapExcel.const_defined?(:CONSTANTS)
  @book = @winapp.Workbooks.Open(file,{ 'ReadOnly' => @options[:read_only] })

  if block
    begin
      yield self
    ensure
      close
    end
  end

  @book
end

Instance Attribute Details

#bookObject (readonly)

Returns the value of attribute book.



5
6
7
# File 'lib/wrap_excel/book.rb', line 5

def book
  @book
end

Class Method Details

.open(file, options = { }, &block) ⇒ Object



70
71
72
# File 'lib/wrap_excel/book.rb', line 70

def self.open(file, options={ }, &block)
  new(file, options, &block)
end

Instance Method Details

#[](sheet) ⇒ Object



42
43
44
45
# File 'lib/wrap_excel/book.rb', line 42

def [] sheet
  sheet += 1 if sheet.is_a? Numeric
  WrapExcel::Sheet.new(@book.Worksheets.Item(sheet))
end

#add_sheet(sheet = nil, options = { }) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/wrap_excel/book.rb', line 53

def add_sheet(sheet = nil, options = { })
  if sheet.is_a? Hash
    options = sheet
    sheet = nil
  end

  new_sheet_name = options.delete(:as)

  after_or_before, base_sheet = options.first || [:after, WrapExcel::Sheet.new(@book.Worksheets.Item(@book.Worksheets.Count))]
  base_sheet = base_sheet.sheet
  sheet ? sheet.Copy({ after_or_before => base_sheet }) : @book.WorkSheets.Add({ after_or_before => base_sheet })

  new_sheet = WrapExcel::Sheet.new(@winapp.Activesheet)
  new_sheet.name = new_sheet_name if new_sheet_name
  new_sheet
end

#closeObject



32
33
34
35
# File 'lib/wrap_excel/book.rb', line 32

def close
  @winapp.Workbooks.Close
  @winapp.Quit
end

#eachObject



47
48
49
50
51
# File 'lib/wrap_excel/book.rb', line 47

def each
  @book.Worksheets.each do |sheet|
    yield WrapExcel::Sheet.new(sheet)
  end
end

#saveObject

Raises:

  • (IOError)


37
38
39
40
# File 'lib/wrap_excel/book.rb', line 37

def save
  raise IOError, "Not opened for writing(open with :read_only option)" if @options[:read_only]
  @book.save
end