From: Masaru Ishii Date: 2000-05-12T14:22:39+09:00 Subject: [ruby-list:22481] Re: win OLE / eRuby なひさん,こんにちは.石井と申します. > 依頼者さん次第ですが,他にも募集しておりますです. > win32oleをご利用の方,よろしくお願いします. 複数あるExcelブックを1つのブックに統合するというスクリプトがあります. これは,Excelファイルを自動生成するとき,分割コンパイルみたいなこと をしたいときに使います.こうすると,複数シートからなるブックを自動生成 するとき,変更されたシートのみ自動生成するので効率がいい,ということです. 例えば,XMLファイルA.xml, B.xmlから 中間ファイルとして1シートのみから なる2つのブックA.xls, B.xlsを xml2xls.rb で自動生成します. c:\> ruby xml2xls.rb -o A.xls A.xml c:\> ruby xml2xls.rb -o B.xls B.xml この後,下のスクリプト(xlsjoin.rb) でA.xls とB.xls を統合してAll.xlsという 2シートからなるブックを作成します. c:\> ruby xlsjoin.rb -o All.xls A.xls B.xls 以下がxlsjoin.rbスクリプトです. Rubyは今までまともに勉強したことがありませんので,何か気が付いた ことがあれば教えてくださいm(_ _)m --- xlsjoin.rb require 'win32ole' class Excel def Excel.runDuring(visible = true, &aBlock) excel = WIN32OLE.new('Excel.Application') WIN32OLE.const_load(excel, Excel) begin excel.visible = visible excel.displayAlerts = FALSE aBlock.call(excel) rescue raise ensure excel.quit end end end class WorkbookJoiner def initialize(workbook) @workbook = workbook @uselessSheetCount = workbook.sheets.count while @uselessSheetCount > 1 @workbook.sheets(@uselessSheetCount).delete @uselessSheetCount -= 1 end end def addWorkbook(workbookToAdd) sheetsToAdd = workbookToAdd.sheets sheetCountToAdd = sheetsToAdd.count lastSheet = @workbook.sheets(@workbook.sheets.count) for i in 1..sheetCountToAdd sheetsToAdd.item(i).copy({'After'=>lastSheet}) lastSheet = @workbook.sheets(@workbook.sheets.count) end if @uselessSheetCount > 0 then @workbook.sheets(@uselessSheetCount).delete @uselessSheetCount -= 1 end end end require 'getopts' outBookName = "xlsjoin.xls" if $OPT_o then outBookName = $OPT_o end outBookName = File.expand_path(outBookName) outBookName.gsub!("/", "\\") Excel.runDuring(false) { |excel| outBook = excel.workbooks.add joiner = WorkbookJoiner.new(outBook) ARGV.each { |bookName| bookName = File.expand_path(bookName) bookName.gsub!("/", "\\") book = excel.workbooks.open({'FileName'=>bookName,'ReadOnly'=>true}) joiner.addWorkbook(book) } outBook.worksheets(1).select outBook.saveAs({'Filename'=>outBookName}) } ---