Roy
Roy

Reputation: 57

How to close files in the ruby gem "Spreadsheet?"

The code below works as it should the FIRST time I run it:

require 'rubygems'
require 'spreadsheet'
book = Spreadsheet.open '/Users/me/myruby/Mywks.xls'
sheet = book.worksheet 0
row = sheet.row(1)
puts row[1]
book.write '/Users/me/myruby/Mywks.xls'

When I run it again I get more messages like:

/Library/Ruby/Gems/1.8/gems/spreadsheet-0.6.5.9/lib/spreadsheet/excel/reader.rb:1149:in `setup': undefined method `read' for false:FalseClass (NoMethodError)
    from /Library/Ruby/Gems/1.8/gems/spreadsheet-0.6.5.9/lib/spreadsheet/excel/reader.rb:121:in `read'

This suggest to me there is a problem with either: 1. The closing of the excel spreadsheet or 2. Writing back to the same spreadsheet I opened.

  1. There is nothing in the ruby gem spreadsheet documentation about closing spreadsheets. Examples end in the "book.write" statement as above, if anything. My search here and elsewhere turned up nothing re closing the xls file in spreadsheet.
  2. The spreadsheet documentation suggest you CAN write back to the same file but suggests maybe you shouldn't. Is that the problem here? If so do I writ to a temporary wks and then rename it?

Upvotes: 5

Views: 4283

Answers (2)

Alexey Novikov
Alexey Novikov

Reputation: 97

You can close file manualy: 1) add somewhere this code:

module Spreadsheet
  class Workbook
    attr_accessor :io
  end
end

2) simply call

@book.io.close

to close file

Upvotes: 0

pguardiario
pguardiario

Reputation: 54984

Try using block syntax, it seems to work for me:

Spreadsheet.open '/Users/me/myruby/Mywks.xls' do |book|
  sheet = book.worksheet 0
  # book should be closed when the block exits
end

Upvotes: 9

Related Questions