Adding Paragraphs and Styles
You can explicitly
format text with precise font names and sizes by assigning them to
the many properties of the Selection object, but
it is less work and a better design to use predefined styles.
It’s far easier to change a style than to adjust 20 different
reporting scripts.
The first thing to do is add a paragraph in a named style. Word has constants for all the standard styles. If you used MakePy to build the support for Word, you could access the built-in styles like this:
>>> from win32com.client import constants >>> mySelection.Style = constants.wdStyleHeading1 >>>
Note that we set the Style property of the current
Range to the correct style constant. This
doesn’t work if you use dynamic dispatch, or if you have your
own custom template with styles that aren’t built into Word.
However, you can query a document at runtime. The following method
gets and keeps a list of all styles actually present in a document:
def getStyleList(self):
# returns a dictionary of the styles in a document
self.styles = []
stylecount = self.wordDoc.Styles.Count
for i in range(1, stylecount + 1):
styleObject = self.wordDoc.Styles(i)
self.styles.append(styleObject.NameLocal)The Style property of a Range
or Selection in Word accepts either a constant or
a string value, so you might as well use the names. Here’s a
useful method:
def addStyledPara(self, text, stylename):
if text[-1] <> '\n':
text = text + '\n'Let’s try:
>>> import easyword >>> w = easyword.WordWrap() >>> w.show() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access