在 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 天的临时许可证。