我正在尝试使用
Ruby读取Excel电子表格文件,但不会读取文件的内容.
这是我的脚本
book = Spreadsheet.open 'myexcel.xls'; sheet1 = book.worksheet 0 sheet1.each do |row| puts row.inspect ; puts row.format 2; puts row[1]; exit; end
它给我如下:
[DEPRECATED] By requiring 'parseexcel','parseexcel/parseexcel' and/or 'parseexcel/parser' you are loading a Compatibility layer which provides a drop-in replacement for the ParseExcel library. This code makes the reading of Spreadsheet documents less efficient and will be removed in Spreadsheet version 1.0.0 #<Spreadsheet::Excel::Row:0xffffffdbc3e0d2 @worksheet=#<Spreadsheet::Excel::Worksheet:0xb79b8fe0> @outline_level=0 @idx=0 @hidden=false @height= @default_format= @formats= []> #<Spreadsheet::Format:0xb79bc8ac> nil
解决方法
它看起来像行,其类是Spreadsheet :: Excel :: Row实际上是一个Excel范围,它或者包括Enumerable或至少暴露了一些可枚举的行为,例如#each.
所以你可以重写你的脚本,如下所示:
require 'spreadsheet' book = Spreadsheet.open('myexcel.xls') sheet1 = book.worksheet('Sheet1') # can use an index or worksheet name sheet1.each do |row| break if row[0].nil? # if first cell empty puts row.join(',') # looks like it calls "to_s" on each cell's Value end
请注意,我有括号的参数,这些日子一般是可取的,并且删除了分号,除非你在一行(你几乎不会这么做)上写多个语句,否则这是不必要的.
这可能是一个更大的脚本的宿醉,但是我会指出,在给定书和sheet1变量的代码中,并不是真正需要,而且Spreadsheet#open是一个块,所以一个更加惯用的Ruby版本可能就像这个:
require 'spreadsheet' Spreadsheet.open('MyTestSheet.xls') do |book| book.worksheet('Sheet1').each do |row| break if row[0].nil? puts row.join(',') end end