Over a million developers have joined DZone.

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.


require 'win32ole'

word = WIN32OLE.new('Word.Application')
#word.Visible = true # uncomment if you want to see it happen
doc = word.Documents.Open('c:\file_to_open.doc')
{
  'name' => 'Tim Morgan',
  'date' => Date.today.strftime('%B %d, %Y'),
  ...
}.each do |key, value|
  word.Selection.HomeKey(unit=6) # start at beginning
  find = word.Selection.Find
  find.Text = "[#{key}]" # text must be in square brackets
  while word.Selection.Find.Execute
    word.Selection.TypeText(text=value)
  end
end
doc.SaveAs('c:\output_file.doc')
doc.Close
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}