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

前端 未结 5 1536
醉话见心
醉话见心 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条回答
  •  死守一世寂寞
    2020-12-28 12:01

    I like the answers so far;
    here's a tested example (slightly modified from here)
    that replaces all occurrences of a string in a Word document:

    import win32com.client
    
    def search_replace_all(word_file, find_str, replace_str):
        ''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''
        wdFindContinue = 1
        wdReplaceAll = 2
    
        # Dispatch() attempts to do a GetObject() before creating a new one.
        # DispatchEx() just creates a new one. 
        app = win32com.client.DispatchEx("Word.Application")
        app.Visible = 0
        app.DisplayAlerts = 0
        app.Documents.Open(word_file)
    
        # expression.Execute(FindText, MatchCase, MatchWholeWord,
        #   MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, 
        #   Wrap, Format, ReplaceWith, Replace)
        app.Selection.Find.Execute(find_str, False, False, False, False, False, \
            True, wdFindContinue, False, replace_str, wdReplaceAll)
        app.ActiveDocument.Close(SaveChanges=True)
        app.Quit()
    
    f = 'c:/path/to/my/word.doc'
    search_replace_all(f, 'string_to_be_replaced', 'replacement_str')
    

提交回复
热议问题