2014-02-24 57 views
2

我需要知道工作簿中是否存在工作表或不使用ruby。用於檢查工作簿中是否存在工作表的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只有當後來其他板材存在拋出一個錯誤消息。

+0

你生氣了使用Ruby? :-)順便說一句,你現在在哪個操作系統?你在使用['win32ole'](http://www.ruby-doc.org/stdlib-2.1.0/libdoc/win32ole/rdoc/WIN32OLE.html)嗎? –

+4

要在stackoverflow上獲得答案,您需要向我們展示您嘗試過的內容。它還有助於定義像「工作表」這樣的術語,給我們一種上下文感。 – Ziggy

+0

憤怒?不,我需要將某些Excel數據更新到特定工作表中的工作簿中。如果工作表丟失,我需要拋出一個錯誤消息。我只使用Windows。 – anurag

回答

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 
+0

@rakshit非常感謝,這正是我需要的。 – anurag

相關問題