O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required