Python 为 Word 文档设置结构

318 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情

前言

要创建合适的专业文档,我们需要为其设置合适的结构。Word 文档通常以段落的形式工作,我们可以引入分隔符和换页符来正确划分文档。

Python 为 Word 文档设置结构

在本节中,我们将学习如何创建结构化的 Word 文档,并引入通过创建不同部分来正确划分文档。

首先,导入 python-docx 模块:

>>> import docx

利用 Document 类创建一个新的文档对象 document

>>> document = docx.Document()

创建文档后,我们首先在第一部分中添加一个段落,并且在段落中我们使用换行符对段落进行分割。创建一个有换行符的段落:

>>> paragraph = document.add_paragraph('A challenge is one of the qualities (requirements) that')
>>> run = paragraph.add_run()
>>> run.add_break(docx.text.run.WD_BREAK.LINE)
>>> paragraph.add_run('may be desired for music')
<docx.text.run.Run object at 0x7f711bd96f90>
>>> paragraph.add_run('Examples are content variability, interactivity and originality.')
<docx.text.run.Run object at 0x7f711bd89310>

在段落中插入换行符和创建一个新段落之间存在细微差别,但对于大多数实际用途而言,它们的作用非常相似。

创建一个分页符并添加一个新段落,引入分页符并不会改变节:

>>> document.add_page_break()
<docx.text.paragraph.Paragraph object at 0x7f711bd96850>
>>> document.add_paragraph('Note that these five dimensions are not orthogonal.')
<docx.text.paragraph.Paragraph object at 0x7f711bd89310>

创建一个新节,并将页面修改为横向页面:

>>> section = document.add_section(docx.enum.section.WD_SECTION.NEW_PAGE)
>>> section.orientation = docx.enum.section.WD_ORIENT.LANDSCAPE
>>> section.page_height, section.page_width = section.page_width, section.page_height
>>> document.add_paragraph('The musical nature of the generated content.')
<docx.text.paragraph.Paragraph object at 0x7f711bd96550>

在更改方向时,我们还需要交换宽度和高度,这是由于每个新节都继承了前一个节的属性,因此需要通过修改属性才能获得新的节属性。

创建另一个新节,并将页面恢复为纵向:

>>> section = document.add_section( docx.enum.section.WD_SECTION.NEW_PAGE)
>>> section.orientation = docx.enum.section.WD_ORIENT.PORTRAIT
>>> section.page_height, section.page_width = section.page_width, section.page_height
>>> document.add_paragraph('The musical style of the content to be generated.')
<docx.text.paragraph.Paragraph object at 0x7f711bd89310>

保存文档 `docx_section.docx 至本地文件系统:

>>> document.save('word_structure.docx')

 

通过打开文档 docx_section.docx 并检查结果部分,观察创建的 Word 文档是否符合预期:

文档首页

检查新页面:

检查新页面

检查页面是否变为横向部分:

横向页面

最后,检查页面是否回到纵向页面:

纵向页面