Python docx库文本对齐
-
21-12-2019 - |
题
我正在使用 python docx 库来操作 word 文档。但是,我找不到如何在该库的文档页面中将线对齐到中心。我用google也找不到。
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 中的文本?
解决方案
随着新版本的python-docx 0.7 https://github.com/python-openxml/python-docx/commit/158f2121bcd2c58b258dec1b83f8fef15316de19添加功能#51:段落。对齐(读/写)现在可以像以下位置对齐一个段落: 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代表右
从评论中编辑2
你不应该像这样硬编码魔术数字。使用 WD_ALIGN_PARAGRAPH.CENTER
获得正确的居中值等。为此,请使用以下导入
from docx.enum.text import WD_ALIGN_PARAGRAPH
其他提示
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), ...
.
参考看这个参考在def段读取文档
不隶属于 StackOverflow