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

Tables

Word tables are sophisticated object hierarchies in their own right, and you can manipulate them to any level of detail. However, there’s also an AutoFormat option for tables that works in a similar way to styles. Here’s the full declaration:

Table.AutoFormat(Format, ApplyBorders, ApplyShading, ApplyFont, ApplyColor,
ApplyHeadingRows, ApplyLastRow, ApplyFirstColumn, ApplyLastColumn, AutoFit)

All you have to do is insert a block of tab-delimited text with the table contents, and call the method to convert text to a table, then call the table’s AutoFormat method. Fortunately, almost all the arguments are optional:

def addTable(self, table, styleid=None):
     # Takes a 'list of lists' of data.
     # first we format the text.  You might want to preformat
     # numbers with the right decimal places etc. first.
     textlines = []
     for row in table:
         textrow = map(str, row)   #convert to strings
         textline = string.join(textrow, '\t')
         textlines.append(textline)
     text = string.join(textlines, '\n')
  
     # add the text, which remains selected
     self.wordSel.InsertAfter(text)
  
     #convert to a table
     wordTable = self.wordSel.ConvertToTable(Separator='\t')
     #and format
     if styleid:
         wordTable.AutoFormat(Format=styleid)

Unfortunately, to specify a style, you need to supply a numeric format constant instead of a name. If you are using MakePy, this is easy; an alternate approach is to use Word’s VB editor to look up the constants. Be warned: some constants vary across different language editions of Word.

Tables can be accessed ...

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