对齐文本/格式文本 - Docx - Python

时间:2017-09-22 00:52:28

标签: python python-2.7 python-docx

我正在寻找一种格式化使用Python生成的报表的方法。我已经审核了Python docx library text align,但这没有用,也没有真正满足我的需求。

我希望做的是格式化一个段落中心,另一个左侧等等。

from docx import Document
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_ALIGN_PARAGRAPH

document = Document()
app_name = "Company App Here"
consultant = "Jerry"

document.add_heading (app_name + "  Report",0)

document.add_paragraph("Testing performed by " + consultant) #How do I align this to the center?

document.add_page_break()

document.add_heading('Executive Summary\n',1)
document.add_paragraph('''\tThe blah blah blah text here''') #Align left and bold this paragraph

document.add_page_break()


document.save('./report.docx')

1 个答案:

答案 0 :(得分:1)

此代码将为您运行

from docx import Document
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_ALIGN_PARAGRAPH

document = Document()
app_name = "Company App Here"
consultant = "Jerry"

document.add_heading (app_name + "  Report",0)

p1=document.add_paragraph("Testing performed by " + consultant)
p1.alignment=WD_ALIGN_PARAGRAPH.CENTER
document.add_page_break()

document.add_heading('Executive Summary\n',1)
p2=document.add_paragraph()
p2.add_run('\tThe blah blah blah text here').bold=True
p2.alignment=WD_ALIGN_PARAGRAPH.LEFT
document.add_page_break()


document.save('./report.docx')

这将生成一个docx(根据问题的要求)。