我正在使用python docx库来操作word文档。但是,我无法找到如何在该库的文档页面中将行与中心对齐。我无法通过谷歌找到。
from docx import Document
document = Document()
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
如何在docx中对齐文本?
答案 0 :(得分:3)
使用新版本的python-docx 0.7 https://github.com/python-openxml/python-docx/commit/158f2121bcd2c58b258dec1b83f8fef15316de19 添加功能#51:Paragraph.alignment(读/写) 现在可以将段落对齐为:http://python-docx.readthedocs.org/en/latest/dev/analysis/features/par-alignment.html
paragraph = document.add_paragraph("This is a text")
paragraph.alignment = 0 # for left, 1 for right, 2 center, 3 justify ....
从评论中进行编辑
实际上左边是0,中心是1,右边是
从评论中编辑2
你不应该硬编码像这样的魔法数字。使用WD_ALIGN_PARAGRAPH.CENTER
获取正确的居中值等。为此,请使用以下导入
from docx.enum.text import WD_ALIGN_PARAGRAPH
答案 1 :(得分:1)
p = document.add_paragraph('A plain paragraph having some ',style='BodyText', breakbefore=False, jc='left')# @param string jc: Paragraph alignment, possible values:left, center, right, both (justified), ...
供参考,请参阅此段reference在def段阅读文档