Question

I need to know whether a sheet exists in the workbook or not using ruby.

code

excel = WIN32OLE.new('Excel.Application') 
excel.visible = false   
workbook = excel.Workbooks.Add(); 
worksheet = workbook.Worksheets.Add() 
workbook.Worksheets("header_new").copy(workbook.Worksheets("header_old")) 

I need to copy the content of header_old into header_new only if the later sheet exists else throw an error message.

Was it helpful?

Solution

Here is a good blog-post for Automating Excel using Ruby :

# Require the WIN32OLE library
require 'win32ole'
# Create an instance of the Excel application object
xl = WIN32OLE.new('Excel.Application')
# Make Excel visible
xl.visible = 1
# Add a new Workbook object
wb = xl.workbooks.add
# Get the first,second Worksheet
ws1,ws2 = wb.worksheets(1),wb.worksheets(2)
# Let rename those sheet
[ws1,ws2].each.with_index(1) { |s,i| s.name = "test_sheet_#{i}" }
# Lets check how many worksheet is present currently
totale_sheet_count = wb.sheets.count

# now let's check if any sheet is having the name, as you are looking for
1.upto(totale_sheet_count).any? { |number| wb.worksheets(number).name == "foo" } # => false
1.upto(totale_sheet_count).any? { |number| wb.worksheets(number).name == "test_sheet_2" } # => true

To understand this you first need to look into the method #any?, #upto and #raise.

Here is a final code to meet your needs :

require 'win32ole'
excel = WIN32OLE.new( 'Excel.Application' )
excel.visible = true
wb = excel.workbooks.open( "path/to/your_excel.xlsx" )
totale_sheet_count = wb.sheets.count
# below line checking if your excel has any worksheet named as "header_new". If it
# find such a named sheet, Enumerable#any method will return true, otherwise false.
bol = 1.upto(totale_sheet_count).any? { |number| wb.worksheets(number).name == "header_new" }  

begin
  raise( RuntimeError, "Required sheet is not present" ) unless bol
  workbook.worksheets("header_new").copy(workbook.worksheets("header_old")) 
rescue RuntimeError => ex
  puts ex.message
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top