Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Find & Replace in Word Document with Ruby

I use this to open a "template" (really just a plain Word document with [text to replace] inside), do the substitutions, and save as a new filename.

   1  
   2  require 'win32ole'
   3  
   4  word = WIN32OLE.new('Word.Application')
   5  #word.Visible = true # uncomment if you want to see it happen
   6  doc = word.Documents.Open('c:\file_to_open.doc')
   7  {
   8    'name' => 'Tim Morgan',
   9    'date' => Date.today.strftime('%B %d, %Y'),
  10    ...
  11  }.each do |key, value|
  12    word.Selection.HomeKey(unit=6) # start at beginning
  13    find = word.Selection.Find
  14    find.Text = "[#{key}]" # text must be in square brackets
  15    while word.Selection.Find.Execute
  16      word.Selection.TypeText(text=value)
  17    end
  18  end
  19  doc.SaveAs('c:\output_file.doc')
  20  doc.Close
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS