使用分区

Word支持以下概念: section ,文档的一部分,具有相同的页面布局设置,例如页边距和页面方向。例如,这就是文档可以包含纵向布局的一些页面和横向布局的其他页面的方式。每一节还定义了应用于该节页面的页眉和页脚。

大多数Word文档只有默认情况下的单个部分,而且大多数文档没有理由更改默认页边距或其他页面布局。但当你 do 需要更改页面布局,您需要了解部分才能完成。

访问部分

文档部分的访问由 sections 属性上 Document 对象:

>>> document = Document()
>>> sections = document.sections
>>> sections
<docx.parts.document.Sections object at 0x1deadbeef>
>>> len(sections)
3
>>> section = sections[0]
>>> section
<docx.section.Section object at 0x1deadbeef>
>>> for section in sections:
...     print(section.start_type)
...
NEW_PAGE (2)
EVEN_PAGE (3)
ODD_PAGE (4)

从理论上讲,一个文档没有任何明确的部分是可能的,尽管我还没有看到这种情况在野外发生。如果您访问的.docx文件数量不可预测,您可能需要使用 len() 检查或 try 阻止以避免未捕获 IndexError 停止程序时出现异常。

添加新节

这个 Document.add_section() 方法允许在文档末尾启动新节。调用此方法后添加的段落和表格将显示在新节中:

>>> current_section = document.sections[-1]  # last section in document
>>> current_section.start_type
NEW_PAGE (2)
>>> new_section = document.add_section(WD_SECTION.ODD_PAGE)
>>> new_section.start_type
ODD_PAGE (4)

截面属性

这个 Section 对象有11个属性,这些属性允许发现和指定页面布局设置。

区段起始类型

Section.start_type 描述节前面的中断类型:

>>> section.start_type
NEW_PAGE (2)
>>> section.start_type = WD_SECTION.ODD_PAGE
>>> section.start_type
ODD_PAGE (4)

价值观 start_typeWD_SECTION_START 枚举。

页面尺寸和方向

三个属性 Section 描述页面尺寸和方向。这些可以一起使用,例如,将截面的方向从纵向更改为横向:

>>> section.orientation, section.page_width, section.page_height
(PORTRAIT (0), 7772400, 10058400)  # (Inches(8.5), Inches(11))
>>> new_width, new_height = section.page_height, section.page_width
>>> section.orientation = WD_ORIENT.LANDSCAPE
>>> section.page_width = new_width
>>> section.page_height = new_height
>>> section.orientation, section.page_width, section.page_height
(LANDSCAPE (1), 10058400, 7772400)

页边距

七个属性 Section 一起指定确定文本在页面上显示位置的各种边距:

>>> from docx.shared import Inches
>>> section.left_margin, section.right_margin
(1143000, 1143000)  # (Inches(1.25), Inches(1.25))
>>> section.top_margin, section.bottom_margin
(914400, 914400)  # (Inches(1), Inches(1))
>>> section.gutter
0
>>> section.header_distance, section.footer_distance
(457200, 457200)  # (Inches(0.5), Inches(0.5))
>>> section.left_margin = Inches(1.5)
>>> section.right_margin = Inches(1)
>>> section.left_margin, section.right_margin
(1371600, 914400)