在 word 中,每个段落都应传达一个独特的想法或观点,帮助以一种读者易于理解的方式来组织信息。插入新段落可以引入新概念或扩展主题的不同方面,使文本更清晰。在本文中,您将学习如何使用 spire.doc for python 在 word 中插入新段落。
安装 spire.doc for python
本教程需要用到 spire.doc for python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 windows 中。
pip install spire.doc
如果您不确定如何安装,请参考:如何在 windows 中安装 spire.doc for python
python 在 word 文档末尾添加段落
要在文档末尾添加一个新段落,需要先通过 document.lastsection 属性获取 word 文档的最后一节,然后再通过 section.addparagraph() 方法在该节末尾添加一个段落。具体步骤如下:
- 创建 document 类的对象。
- 使用 document.loadfromfile() 方法加载 word 文档。
- 使用 document.lastsection 属性获取文档的最后一节。
- 使用 section.addparagraph() 方法在该节末尾添加一个段落,然后使用 paragraph.appendtext() 方法添加文本到段落中。
- 创建一个 paragraphstyle 对象,并设置段落文本的字体名称、大小和样式等。
- 使用 paragraph.applystyle() 方法应用段落样式。
- 使用 document.savetofile() 方法保存结果文档。
- python
from spire.doc import *
from spire.doc.common import *
# 创建document对象
doc = document()
# 加载word文档
doc.loadfromfile("测试.docx")
# 获取最后一节
section = doc.lastsection
# 在该节末尾添加段落
para = section.addparagraph()
para.appendtext("在文档末尾添加新段落。")
# 设置段落样式
style = paragraphstyle(doc)
style.name = "style1"
style.characterformat.fontname = "宋体"
style.characterformat.fontsize = 12
style.characterformat.textcolor = color.get_blue()
style.characterformat.bold= true
doc.styles.add(style)
para.applystyle("style1")
para.format.beforespacing = 10
# 保存结果文件
doc.savetofile("添加段落.docx", fileformat.docx2016)
doc.close()
python 在 word 中的指定位置插入段落
您还可以先添加新段落,然后通过 section.paragraphs.insert(int index, iparagraph paragraph) 方法将其插入到文档指定位置处。具体步骤如下:
- 创建 document 类的对象。
- 使用 document.loadfromfile() 方法加载 word 文档。
- 使用 document.sections[] 属性获取指定节。
- 使用 section.addparagraph() 方法添加段落,然后使用 paragraph.appendtext() 方法添加文本到段落中。
- 设置段落文本的字体名称、大小和样式等。
- 使用 section.paragraphs.insert(int index, iparagraph paragraph) 方法在指定索引处插入新添加的段落。
- 使用 document.savetofile() 方法保存结果文档。
- python
from spire.doc import *
from spire.doc.common import *
# 创建document对象
doc = document()
# 加载word文档
doc.loadfromfile("测试.docx")
# 获取第一节
section = doc.sections[0]
# 添加段落并设置其文本内容
para = section.addparagraph()
textrange = para.appendtext("在文档中间指定位置插入段落。")
# 设置字体名称、大小、颜色和样式
textrange.characterformat.textcolor = color.get_blue()
textrange.characterformat.fontname = "宋体"
textrange.characterformat.fontsize = 14
textrange.characterformat.underlinestyle = underlinestyle.single
# 将添加的段落插入作为第三段
section.paragraphs.insert(2, para)
# 设置段落间距
para.format.afterspacing = 10
# 保存结果文件
doc.savetofile("插入段落.docx", fileformat.docx2016)
doc.close()
申请临时 license
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用javascript。获取有效期 30 天的临时许可证。