加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:08:18 所属栏目:百科 来源:网络整理
导读:我正在尝试使用 Ruby读取Excel电子表格文件,但不会读取文件的内容. 这是我的脚本 book = Spreadsheet.open 'myexcel.xls';sheet1 = book.worksheet 0sheet1.each do |row| puts row.inspect ; puts row.format 2; puts row[1]; exit;end 它给我如下: [DEPRE
我正在尝试使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读