[Tutor] Edit a Word document programmatically

Mark Tolonen metolone+gmane at gmail.com
Wed Oct 15 04:26:51 CEST 2008


These two lines connect to Word.  The EnsureDispatch makes sure Word constants work later:

>>> import win32com.client
>>> word = win32com.client.gencache.EnsureDispatch('Word.Application')

Then record a Word macro to do what you want (this was a find/replace all):

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "fox"
        .Replacement.Text = "cat"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

Then translate to Python:

>>> find = word.Selection.Find
>>> find.ClearFormatting()
>>> find.Replacement.ClearFormatting()
>>> find.Text = 'fox'
>>> find.Replacement.Text = 'cat'
>>> find.Forward = True
>>> find.Wrap = win32com.client.constants.wdFindContinue
>>> find.Execute(Replace=win32com.client.constants.wdReplaceAll)
True

-Mark



"URBAN LANDREMAN" <ulandreman at msn.com> wrote in message news:BAY111-W364B7C4C69E8579B0F9A9DC2310 at phx.gbl...
  Good morning,

  I'm trying to write some Python code to programmatically do a Find and Replace of a string within a Microsoft Word document.
  Any suggestions on where I could look to find how to do such a function?

  Thank you.


  Urban Landreman 




------------------------------------------------------------------------------


  _______________________________________________
  Tutor maillist  -  Tutor at python.org
  http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081014/33078d59/attachment.htm>


More information about the Tutor mailing list