如何使用Ruby阅读Excel电子表格的内容?

我试图用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=# @outline_level=0 @idx=0 @hidden=false @height= @default_format= @formats= []> # nil 

我需要获取文件的实际内容。 我究竟做错了什么?

它看起来像row ,其类是Spreadsheet::Excel::Row实际上是一个Excel Range ,它包括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 

请注意,我已经使用括号参数,这些日子通常是可取的,并且删除了分号,除非你在一行上写了多个语句(你应该很少 – 如果有的话),这是不必要的。

它可能是一个较大的脚本的宿醉,但我会指出,在代码中给出了booksheet1变量并不是真正需要的,并且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 

我认为您不需要parseexcel,只require 'spreadsheet'

你读过这本指南 ,它非常容易理解。

它是一个单行文件吗? 如果是这样,你需要:

 puts row[0]; 
Interesting Posts