python-docx如何设置标题号?

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

我尝试使用此代码

paragraph.insert_paragraph_before(style='Heading 2', text='heading2'),

在我的docx中自动设置标题编号。像1.2,但我想要3.1。 如何设置我给的号码?

在docx中设置我的号码的方法

python python-docx heading
2个回答
0
投票

为每个自定义标题编号创建新样式。在 Word 中,打开 .docx。使用这些样式并根据需要设置编号,然后将 .docx 保存为 .dotx 文件。最后,在您的 python-docx 代码中,在创建新文档时,使用此 .dotx 文件作为模板

from docx import Document

dox = Document('template.dotx')
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.add_text('This is a custom heading')
run.style = doc.styles['Custom Heading 1']
doc.save('output.docx')

0
投票

要使用

python-docx
在 Word 文档中手动设置标题编号,您需要将具有所需编号的标题作为文本的一部分插入。不幸的是,
python-docx
没有提供直接操作标题数字的方法,但您可以通过在标题文本本身中包含数字来实现所需的结果。

具体操作方法如下:

  1. 插入带有自定义编号的标题: 修改您的代码以直接在文本中包含所需的标题编号:
from docx import Document

# Create a new Document or open an existing one
doc = Document()

# Insert a heading with a custom number
heading_text = '3.1 heading2'
doc.add_heading(heading_text, level=2)

# Save the document
doc.save('custom_heading.docx')
  1. 确保格式正确: 如果您想确保编号与其他标题正确对齐,您可以添加手动换行符或对其进行格式化以匹配文档的样式。

完整示例:

这是在新文档中添加自定义编号标题的完整示例:

from docx import Document

# Create a new Document
doc = Document()

# Add a title
doc.add_heading('Document Title', level=1)

# Add the custom numbered heading
heading_text = '3.1 Custom Heading'
doc.add_heading(heading_text, level=2)

# Add some content under the heading
doc.add_paragraph('This is some text under the custom heading.')

# Save the document
doc.save('custom_numbered_heading.docx')

在此示例中:

  • doc.add_heading(heading_text, level=2)
    在第 2 级添加带有自定义文本
    3.1 Custom Heading
    的标题(标题 2)。
  • 您可以根据需要继续添加其他内容。
© www.soinside.com 2019 - 2024. All rights reserved.