Win32OLEでCOMプログラミング
仕様書的なもの?がWordで投げられて来るのですが(勘弁 ^^;)
そんなドキュメントを、Win32OLEモジュールを使ってrubyで
検索、抜き出し、表示って言うのを一日中やってました。
<目的>
カレントディレクトリにあるワードファイルから
【項目名】の書式で書かれた文字列を抜き出し表示(とりあえず標準出力)。
require 'win32ole' require 'FileSystemObject.rb' require 'WordObject.rb' def saerch_word(filename,search_str) results = [] fileSystem = FileSystemObject.instance path = fileSystem.getFolder('.').path wordObj = WordObject.instance wordObj.Visible = true #Wordファイルを読み取り専用で開く wordObj.Documents.Open({'filename'=>path + "\\" + filename, 'readOnly'=> true}) findObj = wordObj.Selection.Find #検索文字列設定 findObj.Text = search_str #ワイルドカード使用の設定 findObj.MatchSoundsLike="False" findObj.MatchAllWordForms="False" findObj.MatchFuzzy="False" findObj.MatchWildcards = "True" #前方一致検索 findObj.Forward="True" while findObj.Execute do results<<wordObj.Selection.Text end wordObj.Documents.Close() return results end dir = Dir.glob("*.doc") dir.each do |filename| saerch_word(filename,"【*】").each do |result| puts result end end
FileSystemObject.rb
module FileSystemObject @instance = nil def FileSystemObject.instance unless @instance then @instance = WIN32OLE.new('Scripting.FileSystemObject') end return @instance end end
WordObject.rb
module WordObject @instance = nil def WordObject.instance unless @instance then @instance = WIN32OLE.new('Word.Application') end return @instance end end
まぁとりあえず、目的を満たせるものができました。
rubyからWordやExcel等のWinアプリをいじるって結構楽しい^^
ちょっと詳しく知りたくなったので
- 作者: arton
- 出版社/メーカー: アスキー
- 発売日: 2000/10
- メディア: 単行本
- 購入: 2人 クリック: 17回
- この商品を含むブログ (29件) を見る
-
-
-
- -
-
-
参考にさせてもらったサイト