Search code examples
pythonms-wordpywin32autoformatting

how can i change the size of a table in word using python (pywin32)


ms word table with python

I am working with python on word tables, i am generating tables, but all of them are

auto fit window..

is it possible to change it to auto fit contents?

i had tried something like this:

table = location.Tables.Add(location,len(df)+1,len(df.columns)
table.AutoFit(AutoFitBehavior.AutoFitToContents)

but it keeps to raise errors


Solution

  • You want to change you table creation to use this:

    //''#Add two ones after your columns
    table = location.Tables.Add(location,len(df)+1,len(df.columns),1,1)
    

    Information about why you need those variables can be read here:

    http://msdn.microsoft.com/en-us/library/office/ff845710(v=office.15).aspx

    But basically, the default behavior is to disable Cell Autofitting and Use Table Autofit to Window. The first "1" enables Cell Autofitting. From the link I posted above, the DefaultTableBehavior can either be wdWord8TableBehavior (Autofit disabled --default) or wdWord9TableBehavior (Autofit enabled). The number comes from opening up Word's VBA editor and typing in the Immediate Window:

    ?Word.wdWord9TableBehavior
    

    Next, from the link, we see another option called AutoFitBehavior. This is defined as:

    Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

    So now we have another term to look up. In the VBA editor's Immediate window again type:

    ?Word.wdAutoFitBehavior.
    

    After the last dot, the possible options should appear. These will be:

    • wdAutoFitContent
    • wdAutoFitFixed
    • wdAutoFitWindow

    AutoFitContent looks to be the option we want, so let's finish up that previous line with:

    ?Word.wdAutoFitBehavior.wdAutoFitContent
    

    The result will be a "1".

    Now you may ask, why do we have to go through all this trouble finding the numerical representations of the values. From my experience, with using pywin32 with Excel, is that you can't get the Built-in values, from the string, most of the time. But putting in the numerical representation works just the same.

    Also, One more reason for why your code may be failing is that the table object may not have a function "Autofit".

    I'm using Word 2007, and Table has the function, AutoFitBehavior. So Change:

     table.AutoFit(AutoFitBehaviour.AutoFitToContent)
    

    To:

    table.AutoFitBehavior(1) 
    //''Which we know the 1 means wd.wdAutoFitBehavior.wdAutoFitContent
    

    Hope I got it right, and this helps you out.