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



我需要知道工作簿中是否存在工作表,是否使用 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中,否则会抛出错误消息。

这里有一篇很好的博客文章,用于Automating Excel使用 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

要理解这一点,您首先需要研究方法#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

最新更新