Python-docx - 添加值后将现有 table 中的单元格内容居中

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

我有一个空 table 的 .docx 模板,我要在其中添加值:

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'

添加这些值后,table 属性 "Centered" 消失,这是标准行为。

如何遍历 table 并再次将所有值居中?我已经用谷歌搜索过,但没有找到任何帮助。例如:不起作用:

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)

非常感谢你的帮助。

单元格上的 .text 属性 完全替换单元格中的文本,包括之前的段落。

"centered" 属性在每个段落上,而不是在单元格上。所以你需要做类似的事情:

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

每个 "new" 段落(分配给 .text 将在每个单元格中留下一个)。