A quick and dirty class for working with Word via COM in Python. By far, not all of the power of Word is available here, but it's a good start for simple tasks.
1
2 from win32com.client import constants, Dispatch
3
4 import pythoncom
5
6 wdStory = 6
7
8 class WordDocument(object):
9 """
10 Some convenience methods for Word documents accessed
11 through COM.
12 """
13
14 def __init__(self, visible=False):
15 self.app = Dispatch("Word.Application")
16 self.app.Visible = visible
17
18 def new(self, filename=None):
19 """
20 Create a new Word document. If 'filename' specified,
21 use the file as a template.
22 """
23 self.app.Documents.Add(filename)
24
25 def open(self, filename):
26 """
27 Open an existing Word document for editing.
28 """
29 self.app.Documents.Open(filename)
30
31 def save(self, filename=None):
32 """
33 Save the active document. If 'filename' is given,
34 do a Save As.
35 """
36 if filename:
37 self.app.ActiveDocument.SaveAs(filename)
38 else:
39 self.app.ActiveDocument.Save()
40
41 def save_as(self, filename):
42 return self.save(filename)
43
44 def print_out(self):
45 """
46 Print the active document.
47 """
48 self.app.Application.PrintOut()
49
50 def close(self):
51 """
52 Close the active document.
53 """
54 self.app.ActiveDocument.Close()
55
56 def quit(self):
57 """
58 Quit Word.
59 """
60 return self.app.Quit()
61
62 def find_and_replace(self, find_str, replace_str):
63 """
64 Find all occurances of 'find_str' and replace with 'replace_str'
65 in the active document.
66 """
67 self.app.Selection.HomeKey(Unit=wdStory)
68 find = self.app.Selection.Find
69 find.Text = find_str
70 while self.app.Selection.Find.Execute():
71 self.app.Selection.TypeText(Text=replace_str)