用于检查工作簿中是否存在工作表的Ruby脚本

时间:2014-02-24 11:04:30

标签: ruby windows excel win32ole

我需要知道工作簿中是否存在工作表,否则使用ruby。

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")) 

我需要将header_old的内容复制到header_new,前提是后面的工作表存在,否则会抛出错误信息。

1 个答案:

答案 0 :(得分:3)

以下是使用Ruby的Automating Excel的一篇很好的博文:

# 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

要理解这一点,首先需要查看方法#any?#upto#raise

以下是满足您需求的最终代码:

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