在 word 中插入段落是创建结构合理、条理清晰文档的一项基本技能。段落可以将大段文字分割开来,使读者更容易顺着思路找到具体信息。在 word 中,您可以添加新段落来表示新观点或添加其他信息。本文将演示如何使用 spire.doc for .net 在 word 文档中插入新段落。
安装 spire.doc for .net
首先,您需要将 spire.doc for .net 包含的 dll 文件作为引用添加到您的 .net 项目中。dll 文件可以从此链接下载,也可以通过 安装。
pm> install-package spire.doc
c# 在 word 文档末尾添加段落
要在文档末尾添加一个新段落,需要先通过 document.lastsection 属性获取 word 文档的最后一节,然后再通过 section.addparagraph() 方法在该节末尾添加一个段落。具体步骤如下:
- 创建 document 类的对象。
- 使用 document.loadfromfile() 方法加载 word 文档。
- 使用 document.lastsection 属性获取文档的最后一节。
- 使用 section.addparagraph() 方法在该节末尾添加一个段落,然后使用 paragraph.appendtext() 方法添加文本到段落中。
- 创建一个 paragraphstyle 对象,并设置段落文本的字体名称、大小和样式等。
- 使用 paragraph.applystyle() 方法应用段落样式。
- 使用 document.savetofile() 方法保存结果文档。
- c#
using spire.doc;
using spire.doc.documents;
using system.drawing;
namespace addparagraph
{
class program
{
static void main(string[] args)
{
//创建document对象
document doc = new document();
//加载word文档
doc.loadfromfile("测试.docx");
//获取最后一节
section section = doc.lastsection;
//在该节末尾添加段落
paragraph para = section.addparagraph();
para.appendtext("在文档末尾添加新段落。");
//设置段落样式
paragraphstyle style = new paragraphstyle(doc);
style.name = "style1";
style.characterformat.fontname = "宋体";
style.characterformat.fontsize = 12;
style.characterformat.textcolor = color.blue;
style.characterformat.bold = true;
doc.styles.add(style);
para.applystyle("style1");
para.format.beforespacing = 10;
//保存结果文件
doc.savetofile("添加段落.docx", fileformat.docx2016);
}
}
}
c# 在 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() 方法保存结果文档。
- c#
using spire.doc;
using spire.doc.documents;
using spire.doc.fields;
using system.drawing;
namespace insertparagraph
{
class program
{
static void main(string[] args)
{
//创建document对象
document doc = new document();
//加载word文档
doc.loadfromfile("测试.docx");
//获取第一节
section section = doc.sections[0];
//添加段落并设置其文本内容
paragraph para = section.addparagraph();
textrange textrange = para.appendtext("在文档中间指定位置插入段落。");
//设置字体名称、大小、颜色和样式
textrange.characterformat.textcolor = color.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);
}
}
}
申请临时 license
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用javascript。获取有效期 30 天的临时许可证。