Heads up: This description was created by AI and might not be 100% accurate.

cell.rb

This Ruby code snippet demonstrates the use of the Roo gem to read data from an Excel spreadsheet in XLSX format. The first line imports the Roo library, which provides a convenient interface for reading and writing Excel files.

The second line creates a new instance of the Roo::Excelx class, which represents the Excel file being opened. The file is located at ‘input/roo/book.xlsx’.

The third line retrieves a reference to a sheet in the Excel file by its name, using the sheet() method. In this case, the sheet’s name is ‘mysheet’.

The fourth and fifth lines retrieve the value of the cell at row 1 and column 1 (the upper left-hand corner) and column 2 (the cell immediately to the right of it). The last_row() method retrieves the number of rows in the sheet, while the last_column() method retrieves the number of columns.

Additional Note

  1. Require ‘roo’:
    • This line imports the roo library into your Ruby script. roo is a versatile library for reading from and writing to spreadsheet files like Excel.
  2. Open Excel File:
    • xlsx = Roo::Excelx.new('./book.xlsx'): This line creates a new instance of Roo::Excelx, specifying the Excel file book.xlsx to work with. It opens the Excel file for reading.
  3. Select Sheet:
    • sh1 = xlsx.sheet('mysheet'): This line selects a specific sheet named 'mysheet' from the Excel file and assigns it to the variable sh1. You can then perform operations on this specific sheet.
  4. Retrieve Cell Values:
    • sh1.cell(1,1): This retrieves the value of the cell in the first row and first column of the selected sheet ('mysheet').
    • sh1.cell(1,2): This retrieves the value of the cell in the first row and second column of the selected sheet ('mysheet').
  5. Get Sheet Information:
    • sh1.last_row: This returns the index of the last row that contains data in the selected sheet ('mysheet').
    • sh1.last_column: This returns the index of the last column that contains data in the selected sheet ('mysheet').

Overall, this code snippet allows you to access specific cell values and obtain information about the structure of the Excel sheet, such as the last row and column indices containing data. This information can be useful for various data processing tasks involving Excel files within your Ruby script.

Ruby code snippet

require 'roo'
#=> true

xlsx = Roo::Excelx.new('input/roo/book.xlsx')
#=> 
<#Roo::Excelx:2170 @tmpdir @shared @filename @sheet_files @sheet_names @sheets @...
sh1 = xlsx.sheet('mysheet')
#=> 
<#Roo::Excelx:2170 @tmpdir @shared @filename @sheet_files @sheet_names @sheets @...
sh1.cell(1,1)
#=> "key"
sh1.cell(1,2)
#=> "value"
sh1.last_row
#=> 7
sh1.last_column
#=> 2

Executed with Ruby 3.4.4.