Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read the content of an Excel spreadsheet using Ruby?

I am trying to read an Excel spreadsheet file with Ruby, but it is not reading the content of the file.

This is my script

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

It is giving me the following:

[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

I need to get the actual content of file. What am I doing wrong?

like image 414
Pavunkumar Avatar asked Jul 22 '10 13:07

Pavunkumar


People also ask

Which method is used to read data from Excel files?

Excel file can be read by Java IO operation. For that, we need to use Apache POI Jar. There are two kinds of a workbook in Excel file, XLSX and XLS files. POI has different Interfaces Workbook, Sheet, Row, Cell.


2 Answers

It looks like row, whose class is Spreadsheet::Excel::Row is effectively an Excel Range and that it either includes Enumerable or at least exposes some enumerable behaviours, #each, for example.

So you might rewrite your script something like this:

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

Note that I've parenthesised arguments, which is generally advisable these days, and removed the semi-colons, which are not necessary unless you're writing multiple statement on a line (which you should rarely - if ever - do).

It's probably a hangover from a larger script, but I'll point out that in the code given the book and sheet1 variables aren't really needed, and that Spreadsheet#open takes a block, so a more idiomatic Ruby version might be something like this:

require 'spreadsheet'    
Spreadsheet.open('MyTestSheet.xls') do |book|
  book.worksheet('Sheet1').each do |row|
    break if row[0].nil?
    puts row.join(',')
  end
end
like image 195
Mike Woodhouse Avatar answered Sep 30 '22 04:09

Mike Woodhouse


I don't think you need to require parseexcel, just require 'spreadsheet'

Have you read the guide, it is super easy to follow.

like image 34
Bryan Ash Avatar answered Sep 30 '22 02:09

Bryan Ash