我需要将嵌入到表格中的一小部分文本居中。
传统上,您将使用以下代码将文本居中
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")
我需要在一行中完成,以避免向表中添加额外的行。
总而言之,我该如何将嵌入到与python docx?
相同的add_run()
函数中的文本行居中
发布于 2020-09-19 02:37:37
编辑以演示表格中文本居中显示
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')
https://stackoverflow.com/questions/63960691
复制相似问题