python-docx 为每个段落设置不同的样式

python-docx to set different styles for every paragraph

我正在尝试为带有 python-docx 的段落设置不同的样式设置,但我总是以相同的样式设置结束所有段落,即使我为每个指定不同的样式设置。

这是我的代码:

def get_operation_word_file(self, request, context):
    import unicodedata
    from django.core.files import File
    from docx import Document
    from docx.shared import Inches, Pt

    document = Document()

    section = document.sections[-1]
    section.top_margin = Inches(0.5)
    section.bottom_margin = Inches(0.5)
    section.left_margin = Inches(0.5)
    section.right_margin = Inches(0.5)

    style = document.styles['Normal']
    font = style.font
    font.name ='Arial'
    font.size = Pt(10)

    company_paragraph = document.add_paragraph("EUROAMERICA TTOO INC").alignment = WD_ALIGN_PARAGRAPH.CENTER
    company_paragraph.style.font.size = Pt(20)
    company_paragraph.style.font.bold = True

    description_paragraph = document.add_paragraph("Operación de {} del día {}".format(operation_type[self.operation_type], self.operation_date)).alignment = WD_ALIGN_PARAGRAPH.CENTER
    description_paragraph.style.font.size = Pt(16)
    description_paragraph.style.font.bold = False

    day_paragraph = document.add_paragraph(weekdays[str(self.get_operation_date().weekday())]).alignment = WD_ALIGN_PARAGRAPH.CENTER
    day_paragraph.style.font.size = Pt(16)
    day_paragraph.style.font.bold = False

    current_directory = settings.MEDIA_DIR
    file_name = "Operaciones {} {}.docx".format(self.operation_type, self.operation_date)
    document.save("{}/{}".format(current_directory, file_name))

    return file_name

在生成的文档中,我添加的三个段落以相同的大小和粗体设置结尾。

为了让每个段落都有自己的样式设置,我不知道我错过了什么。

通过引用将样式应用于段落,而不是通过复制其属性。因此,如果您的所有段落都具有 "Normal" 样式,则它们都会获得 "Normal" 最终的样式,这是您最后的设置。

因此,您需要为每个需要看起来不同的段落使用不同的样式,或者您可以直接将格式应用于段落,而不使用样式。后一种方法可能更适合文档中唯一的段落。

所有可以在样式上设置的格式特征也可以直接应用。

python-docx 文档中介绍了样式的使用:
https://python-docx.readthedocs.io/en/latest/user/styles-using.html