使用 python docx 将文本居中

我需要将嵌入表格中的一小段文本居中。


传统上,您可以使用以下代码将文本居中


from docx.enum.text import WD_ALIGN_PARAGRAPH


paragraph = document.add_paragraph("text here")

paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

但是,因为我还需要更改字体和大小,所以我需要将该文本添加到函数中add_run()。这意味着上面的代码不再有效,它甚至不会给出错误,它只是不执行任何操作。


我当前的代码是


from docx.enum.text import WD_ALIGN_PARAGRAPH

...

paragraph = row.cells[idx].add_paragraph().add_run("text here")

paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER    #this line dose not work

限制我获得所需结果的另一件事是,实际上paragraph = document.add_paragraph()会在表中添加一行,这会破坏表的尺寸,这意味着以下代码将不令人满意:


paragraph = document.add_paragraph()

paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

paragraph.add_run("text here")

我需要它在一行中完成,以避免在表中添加额外的行。


因此,在夏季,我如何将已嵌入add_run()函数中的一行文本居中于同一行python docx?


拉丁的传说
浏览 173回答 1
1回答

小怪兽爱吃肉

编辑为演示居中表格中的文本from docx import Documentfrom docx.enum.text import WD_ALIGN_PARAGRAPHdocument = Document('demo.docx')for table in document.tables:    for row in table.rows:        for cell in row.cells:            for para in cell.paragraphs:                para.alignment = WD_ALIGN_PARAGRAPH.CENTER                para.add_run("text here")document.save('demo.docx')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python