使用python-docx处理word.docx文件(4)

使用节

Word中支持的概念部分,具有相同的页面布局设置,如边距和页面方向文档的一个部门。例如,这就是文档如何包含纵向布局的某些页面和横向布局的其他页面的方式。

大多数Word文档默认只有一个部分,而且,大多数文档没有理由更改默认边距或其他页面布局。但是,当您确实需要更改页面布局时,您需要了解各个部分才能完成它。

访问单元

对象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_type是成员WD_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)

猜你喜欢

转载自www.cnblogs.com/xconline/p/11919735.html