使用節
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)