Search code examples
docxpython-docx

Python-docx - Center a cell content in an existing table after adding values


I have a .docx template with an empty table, where I am adding values:

def manipulate_table():

table = doc.tables[0]

table.cell(0, 0).text = 'A'
table.cell(0, 1).text = 'B'
table.cell(0, 2).text = 'C'
table.cell(0, 3).text = 'D'

After adding these values, the the table attribute "Centered" is gone, which is standard behaviour.

How can I loop through my table and center all values again? I've already Googled, but found nothing helpful. E.g.: does not work:

for cell in ....????:
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcVAlign = OxmlElement('w:vAlign')
    tcVAlign.set(qn('w:val'), "center")
    tcPr.append(tcVAlign)

I appreciate all your help.


Solution

  • The .text property on a cell completely replaces the text in the cell, including the paragraph(s) that were there before.

    The "centered" attribute is on each paragraph, not on the cell. So you need to do something like:

    from docx.enum.text import WD_ALIGN_PARAGRAPH
    cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
    

    to each of the "new" paragraphs (assigning to .text will leave you with exactly one in each cell).