如何使用python-docx在单词中添加分节符



我一直在尝试使用python-docx在word文档中添加一个分节符。我基本上想在每个具有style="的段落之前添加一个分节符;标题1";。我已经写了以下代码。代码如下:

1( 获取的段落总数

2( 找到style="的段落的索引;标题1";

3( 在具有style="的段落之前的段落中添加一个游程;标题1";

4( 为运行添加分段中断

z=len(doc.paragraphs)
for i in range(0,z):
if doc.paragraphs[i].style.name == "Heading 1":
run_new=doc.paragraphs[i-1].add_run()
run_new.add_break(docx.enum.text.WD_BREAK.SECTION_NEXT_PAGE)

但它给了我这个错误。

Traceback (most recent call last):
File "D:/Pycharm Projects/pydocx/trial4.py", line 8, in <module>
run_new.add_break(docx.enum.text.WD_BREAK.SECTION_NEXT_PAGE)
File "D:Pycharm Projectspydocxenvlibsite-packagesdocxtextrun.py", line 42, in add_break
}[break_type]
KeyError: 2

我应该如何添加分段中断?

python-docx目前不支持在任意位置插入分节符。您只能在文档末尾添加一个新部分,通常是在从上到下生成新文档的过程中。

>>> new_section = document.add_section(WD_SECTION.ODD_PAGE)
>>> new_section.start_type
ODD_PAGE (4)

有关在文档页面上添加部分的详细信息,请点击此处:
https://python-docx.readthedocs.io/en/latest/user/sections.html

最新更新