借助 Spire.Doc,开发人员可以轻松地将多个 word 文档合并为一个word 文档。合并文档后,您可能需要插入注释或新段落以添加一些描述。本文解释并描述了如何使用 Spire.Doc 在 C# 中的现有 word 文档中插入新段落。
Spire.Doc for.NET 最新下载https://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); } } }