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

标签 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 中,否则会抛出错误消息。

最佳答案

这是 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

关于用于检查工作簿中是否存在工作表的 Ruby 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21985896/

相关文章:

c - Rubyinline 为 RARRAY_LEN 返回错误结果

windows - Docker-compose 无效绑定(bind)安装规范 "/rootfs:ro": invalid volume specification

c# - 如何检查是否允许用户读/写特定的注册表项?

excel - 在 VBA 中输入键 <> 值对的非常简单的方法是什么?

java - 重新定义命名的 Excel 范围然后使用 Apache POI 保存

mysql - 使用 DataMapper 和 MySQL 数据库设置 Padrino

ruby - 如何在不使用While的情况下删除左侧重复的字符串?

ruby-on-rails - 使用 Ruby 别名扩展 Gem

.net - 如何从 .NET 应用程序中的 FTP 协议(protocol)获取目录文件大小

Python 和 Excel - 检查文件是否打开