Python Docx - 如何对标题进行编号?

问题描述 投票:0回答:5

有一个很好的 Python Docx 示例

我使用了多个

document.add_heading('xxx', level=Y)
,当我在 MS Word 中打开生成的文档时,可以看到级别是正确的。

我没有看到编号,例如 1、1.1、1.1.1 等,我只看到标题文本。

如何使用 Docx 显示标题编号?

python python-docx
5个回答
4
投票

字母数字标题前缀是根据标题的大纲样式和级别自动创建的。设置轮廓样式并插入正确的级别,您将获得编号。

来自文档:

_NumberingStyle 对象类 docx.styles.style._NumberingStyle[source] 编号样式。还没有 已实施。

但是,如果您这样设置标题:

paragraph.style = document.styles['Heading 1']

那么它应该默认为该标题的潜在编号样式。


2
投票

使用 python docx 有一个很好的方法可以实现标题枚举等复杂操作。以下是如何进行:

  1. 在 Word 中创建一个新的空白文档,并在其中定义复杂的个人多级列表。
  2. 将空白文档另存为
    my_template.docx
  3. 根据模板在 python 脚本中创建文档:
    from docx import Document

    document = Document("my_template.docx")
    document.add_heading('My first numbered heading', level=1)

瞧,您可以生成带有编号标题的完美文档。


0
投票

这个答案对你很有帮助

首先你需要像这样新建一个没有数字的标题

paragraph = document.add_paragraph()
paragraph.style = document.styles['Heading 4']

然后你就会有这样的xml单词

<w:pPr>
<w:pStyle w:val="4"/>
</w:pPr>

然后您可以访问 xml 单词“pStyle”属性并使用代码下更改它

header._p.pPr.pStyle.set(qn('w:val'), u'4FDD')

最后,打开word文件你就会得到你想要的!!!


0
投票

似乎python-docx没有提取数字标题的功能,所以我创建了它,请参阅我的github: https://github.com/nguyendangson/extract_number_heading_python-docx


-1
投票
def __str__(self):
    if self.nivel == 1: 
        return str(Level.count_1)+'.- '+self.titulo
    elif self.nivel==2: #Imprime si es del nivel 2
        return str(Level.count_1)+'.'+str(Level.count_2)+'.- '+self.titulo
    elif self.nivel==3: #Imprime si es del nivel 3
        return str(Level.count_1)+'.'+str(Level.count_2)+'.'+str(Level.count_3)+'.- '+self.titulo        
© www.soinside.com 2019 - 2024. All rights reserved.