Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 738
ProjektWeinheim Avatar asked Oct 28 '25 17:10

ProjektWeinheim


1 Answers

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

like image 83
scanny Avatar answered Oct 31 '25 11:10

scanny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!