I have simple script that should read excel and print two cells:
require 'rubygems'
gem 'ruby-ole','1.2.11.4'
require 'spreadsheet'
class Filter
# Gets zipcode range
def get_zipcode_range
wb = Spreadsheet.open "../data/zipcode_range.xls"
sheet = wb.worksheet 0
[sheet.cell(0, 0), sheet.cell(0, 1)]
end
end
f = Filter.new
puts f.get_zipcode_range
File structure is as follows:
FilterExcel
data
zipcode_range.xls
lib
filter.rb
When I open command prompt and go to FilterExcel\lib and run:
ruby filter.rb
It gives expected output:
3911AW
3911ZZ
But when I run script from projects root folder, FilterExcel, then it raises error:
C:\Documents and Settings\Erik\FilterExcel>ruby lib\filter.rb C:/Ruby193/lib/ruby/gems/1.9.1/gems/spreadsheet-0.7.4/lib/spreadsheet.rb:68:in 'initialize': No such file or directory - ../data/zipcode_range.xls (Errno::ENOENT) from C:/Ruby193/lib/ruby/gems/1.9.1/gems/spreadsheet-0.7.4/lib/spreadsheet.rb:68:in 'open' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/spreadsheet-0.7.4/lib/spreadsheet.rb:68:in 'open' from lib/filter.rb:56:in 'get_zipcode_range' from lib/filter.rb:63:in ''
P.S. I use Windows XP if that matters.
You should use File.expand_path docs:
wb = Spreadsheet.open File.expand_path("../data/zipcode_range.xls", __FILE__)
Assuming, that the file you posted lies in the same directory as data/. If data/ is in the parent directory of your current Ruby file, go up twice:
wb = Spreadsheet.open File.expand_path("../../data/zipcode_range.xls", __FILE__)
The first ../ always neutralizes the __FILE__ when using File.expand_path this way. If you are not sure, make a debugging output of the file path that was generated:
puts File.expand_path("../data/zipcode_range.xls", __FILE__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With