Can I use Win32 COM to replace text inside a word document?

前端 未结 5 1535
醉话见心
醉话见心 2020-12-28 10:58

I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common str

5条回答
  •  旧时难觅i
    2020-12-28 11:37

    See if this gives you a start on word automation using python.

    Once you open a document, you could do the following.
    After the following code, you can Close the document & open another.

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "test"
        .Replacement.Text = "test2"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    

    The above code replaces the text "test" with "test2" and does a "replace all".
    You can turn other options true/false depending on what you need.

    The simple way to learn this is to create a macro with actions you want to take, see the generated code & use it in your own example (with/without modified parameters).

    EDIT: After looking at some code by Matthew, you could do the following

    MSWord.Documents.Open(filename)
    Selection = MSWord.Selection
    

    And then translate the above VB code to Python.
    Note: The following VB code is shorthand way of assigning property without using the long syntax.

    (VB)

    With Selection.Find
        .Text = "test"
        .Replacement.Text = "test2"
    End With
    

    Python

    find = Selection.Find
    find.Text = "test"
    find.Replacement.Text = "test2"
    

    Pardon my python knowledge. But, I hope you get the idea to move forward.
    Remember to do a Save & Close on Document, after you are done with the find/replace operation.

    In the end, you could call MSWord.Quit (to release Word object from memory).

提交回复
热议问题