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

标签 python python-docx

我尝试使用 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

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

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

最佳答案

样式通过引用应用于段落,而不是通过复制其属性。因此,如果您的所有段落都有“正常”样式,它们都会获得“正常”最终的样式,这是您的最后一个设置。

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

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

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

关于python-docx 为每个段落设置不同的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130266/

相关文章:

python - Scrapy 的 yield 还是返回?

python - pyqt在滚动区域展开网格

python - 将 Unicode 写入 .docx 文件

python - 有没有办法读取.docx文件包括使用python-docx的自动编号

Python Coverage - 不覆盖函数内容,只覆盖定义

python - 没有名为 ev3dev2 的模块

python - 如何查看 python-docx 包生成的 XML

创建word文档时python-docx style_id错误

python-docx中心表内容

python - 编译 - OsError : Cannot load native module 'Cryptodome.Cipher._raw_ecb'