![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Expert Programmer
|
Reading/Writing Word Documents in Python (with win32com.client?)
I have a MS Word document that I am using as a template. After a test is run, certain parts of the Word document need to be replaced with the test results. For example, there is a section in the Word document that looks similar to:
Test Name Test Case # Description of Test Test Procedure # ... Does anyone know what the best way to modify a Word document in Python is? I have installed the Win32 Extensions for Python, but it is very difficult to figure out how to use. So far the best reference I have found is Automating Word Using the Word Object Model MSDN reference, which helps a little, but the code is in VB/C# and I don't know where some of the objects come from; eg: object replaceAll = Word.WdReplace.wdReplaceAll; I read somewhere using Word Macros may be easier. Is this true? If so, how would I go about writing/running a Macro from Python? Or is there another, easier way to do this? Here's what I have so far: import win32com.client
w = win32com.client.Dispatch("Word.Application")
w.Documents.Open(r"C:\Documents and Settings\jboyle\Desktop\python_scripts\ms.doc")
doc = w.ActiveDocument
w.Selection.Find.ClearFormatting()
w.Selection.Find.Text = 'word'
w.Selection.Find.Replacement.ClearFormatting()
w.Selection.Find.Replacement.Text = 'potato'
#w.Selection.Find.Execute( what goes here??? )
w.Quit() |
|
|
|
|
|
#2 |
|
Expert Programmer
|
Thanks for all your help
I finally figured it out myself, thanks mostly to this example. import os
import win32com.client
app = win32com.client.Dispatch("Word.Application")
app.Visible = 0
app.DisplayAlerts = 0
def search_replace(file, find_str, replace_str):
app.Documents.Open(file)
app.Selection.Find.Text = find_str
found = app.Selection.Find.Execute()
doc = app.ActiveDocument
if found:
app.Selection.TypeText(replace_str)
doc.Close(SaveChanges=True)
else:
doc.Close(SaveChanges=False)
return found
f = 'C:\path\to\mswordfile.doc'
print search_replace(f, 'meringuay', 'charlie-horse')
app.Quit() |
|
|
|
|
|
#3 |
|
Expert Programmer
|
This function is similar to the last one but instead of replacing only the first instance of the word, it replaces all instances of the word. It uses the extended Find.Execute method (11 arguments in all!) instead.
wdFindContinue = 1
wdReplaceAll = 2
# expression.Execute(FindText, MatchCase, MatchWholeWord,
# MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward,
# Wrap, Format, ReplaceWith, Replace)
def search_replace_all(file, find_str, replace_str):
app.Documents.Open(f)
app.Selection.Find.Execute(find_str, False, False, False, False, False, \
True, wdFindContinue, False, replace_str, wdReplaceAll)
app.ActiveDocument.Close(SaveChanges=True) |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|