Ruby Quick Reference

Quick reference for efficient coding

View the Project on GitHub YumaYX/RubyQuickReference

cell.rb(roo)

  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.

Execution:

require 'roo'
#=> true

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

Executed with Ruby 3.3.5