【问题标题】:How to add a Sectional Break in word using python-docx如何使用 python-docx 在 word 中添加分节符
【发布时间】:2021-06-23 05:14:53
【问题描述】:

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

1)获取段落总数

2)找到style = "heading 1"的段落的索引

3) 在 style = "heading 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 Projects\pydocx\env\lib\site-packages\docx\text\run.py", line 42, in add_break
    }[break_type]
KeyError: 2

我应该如何添加分节符?

【问题讨论】:

    标签: python ms-word python-docx


    【解决方案1】:

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

    >>> 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

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多