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アプリをいじるって結構楽しい^^
ちょっと詳しく知りたくなったので

Rubyを256倍使うための本 邪道編

Rubyを256倍使うための本 邪道編

この本を読んでみようと思います。

        • -

参考にさせてもらったサイト