<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: msword code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Thu, 24 Jul 2008 07:53:11 GMT</pubDate>
    <description>DZone Snippets: msword code</description>
    <item>
      <title>Find &amp; Replace in Word Document with Ruby</title>
      <link>http://snippets.dzone.com/posts/show/4747</link>
      <description>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.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'win32ole'&lt;br /&gt;&lt;br /&gt;word = WIN32OLE.new('Word.Application')&lt;br /&gt;#word.Visible = true # uncomment if you want to see it happen&lt;br /&gt;doc = word.Documents.Open('c:\file_to_open.doc')&lt;br /&gt;{&lt;br /&gt;  'name' =&gt; 'Tim Morgan',&lt;br /&gt;  'date' =&gt; Date.today.strftime('%B %d, %Y'),&lt;br /&gt;  ...&lt;br /&gt;}.each do |key, value|&lt;br /&gt;  word.Selection.HomeKey(unit=6) # start at beginning&lt;br /&gt;  find = word.Selection.Find&lt;br /&gt;  find.Text = "[#{key}]" # text must be in square brackets&lt;br /&gt;  while word.Selection.Find.Execute&lt;br /&gt;    word.Selection.TypeText(text=value)&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;doc.SaveAs('c:\output_file.doc')&lt;br /&gt;doc.Close&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 12 Nov 2007 14:48:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4747</guid>
      <author>timmorgan (Tim Morgan)</author>
    </item>
  </channel>
</rss>
