Word控件Spire.Doc 【段落处理】教程(十):如何在 C# 中将新段落插入到 Word 文档中

借助 Spire.Doc,开发人员可以轻松地将多个 word 文档合并为一个word 文档。合并文档后,您可能需要插入注释或新段落以添加一些描述。本文解释并描述了如何使用 Spire.Doc 在 C# 中的现有 word 文档中插入新段落。

Spire.Doc for.NET 最新下载icon-default.png?t=M7J4https://www.evget.com/product/3368/download

下面的示例演示如何将段落插入到文档中。

第 1 步:创建一个新文档并从文件加载。

Document document = new Document();
document.LoadFromFile("sample.docx", FileFormat.Docx);

第 2 步:附加文本并设置字体格式。

Paragraph paraInserted = new Paragraph(document);
TextRange textRange1 = paraInserted.AppendText("This is a inserted paragraph, I want to insert this paragraph in the start of document.");
textRange1.CharacterFormat.TextColor = Color.Blue;
textRange1.CharacterFormat.FontSize = 15;
textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;

第 3 步:插入新段落。

document.Sections[0].Paragraphs.Insert(0, paraInserted);

第 4 步:将文档保存到文件中。

document.SaveToFile("result.docx", FileFormat.Docx);

有效截图

完整代码

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertParagh
{
class Program
{

static void Main(string[] args)
{
Document document = new Document();
document.LoadFromFile("sample.docx", FileFormat.Docx);

Paragraph paraInserted = document.Sections[0].AddParagraph();
TextRange textRange1 = paraInserted.AppendText("This is a inserted paragraph, I want to insert this paragraph in the start of document.");
textRange1.CharacterFormat.TextColor = Color.Blue;
textRange1.CharacterFormat.FontSize = 15;
textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;

document.Sections[0].Paragraphs.Insert(0, document.Sections[0].Paragraphs[document.Sections[0].Paragraphs.Count - 1]);

document.SaveToFile("result.docx", FileFormat.Docx);
}
}
}

猜你喜欢

转载自blog.csdn.net/m0_67129275/article/details/126617514#comments_27583779
今日推荐