我需要將嵌入表格中的一小段文本居中。傳統上,您可以使用以下代碼將文本居中from docx.enum.text import WD_ALIGN_PARAGRAPHparagraph = 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.CENTERparagraph.add_run("text here")我需要它在一行中完成,以避免在表中添加額外的行。因此,在夏季,我如何將已嵌入add_run()函數中的一行文本居中于同一行python docx?
1 回答

小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
編輯為演示居中表格中的文本
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = 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')
添加回答
舉報
0/150
提交
取消