python-3.xpython-docxrow-height

Python Docx Table row height


So column width is done using cell width on all cells in one column ike this:

from docx import Document
from docx.shared import Cm

file = /path/to/file/
doc = Document(file)
table = doc.add_table(4,2)
for cell in table.columns[0].cells:
    cell.width = Cm(1.85)

however, the row height is done using rows, but I can't remember how I did it last week.

Now I managed to find a way to reference the rows in a table, but can't seem to get back to that way. It is possible to change the height by using the add_row method, but you can't create a table with no rows, so the the top row will always be the default height, which about 1.6cms.

There is a way to access paragraphs without using add_paragraph, does anyone know how to access the rows without using the add_row method because it was that that I used to set row height in a table as a default.

I have tried this but it doesn't work:

row = table.rows
row.height = Cm(0.7)

but although this does not give an error, it also has no effect on the height.


Solution

  • table.rows is a collection, in particular a sequence, so you need to access each row separately:

    for row in table.rows:
        row.height = Cm(0.7)
    

    Also check out row.height_rule for some related behaviors you have access to:
    https://python-docx.readthedocs.io/en/latest/api/table.html#row-objects

    When you assign to table.rows.height, it just adds a .height instance attribute that does nothing. It's one of the side-effects of a dynamic language like Python that you encounter a mysterious behavior like this. It goes away as you gain more experience though, at least it has for me :)