在上一篇文章中介绍了关于C#如何插入Word书签、插入图片或表格到word、删除word书签等内容,本篇文章将继续介绍C#操作word书签的方法。下面的示例中将介绍
- C# 如何读取Word书签
- C# 如何替换Word书签
工具使用
- Spire.Doc for .NET 6.1
- Visual Studio
示例代码
原文档中的书签内容:
【C#】
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System;namespace GetTextOfBookmark_Doc {class Program{static void Main(string[] args){//实例化Document类,加载测试文档Document doc = new Document();doc.LoadFromFile("test.docx");//初始化BookmarkNavigator类对象BookmarksNavigator navigator = new BookmarksNavigator(doc);//定位到指定书签位置,获取书签位置的文档内容navigator.MoveToBookmark("bookmark1");TextBodyPart textBodyPart = navigator.GetBookmarkContent();//遍历书签内容中的子项目,并将文本信息提取至string类型变量中string text = null;foreach (var item in textBodyPart.BodyItems){if (item is Paragraph){foreach (var childObject in (item as Paragraph).ChildObjects){if (childObject is TextRange){text += (childObject as TextRange).Text;}}}}//控制台输出文本Console.WriteLine(text);Console.ReadLine();}} }
读取结果如下:
2. 替换书签内容
【C#】
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields;namespace EditOrReplaceBookmark_Doc {class Program{static void Main(string[] args){//创建Document类实例,加载文档 Document document = new Document();document.LoadFromFile("test.docx");Section sec = document.AddSection();//添加sectionsec.AddParagraph().AppendText("Welcome Back, \n My Friend!"); //添加段落到section,并添加字符串内容//获取段落内容 ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase;ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;//实例化类TextBodySelection和TextBodyPartTextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph);TextBodyPart part = new TextBodyPart(selection);BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);//实例化BookmarksNavigator类 bookmarkNavigator.MoveToBookmark("bookmark1", true, true);//定位到书签“bookmark1”所在段落的位置bookmarkNavigator.DeleteBookmarkContent(true);//删除原有书签位置的内容bookmarkNavigator.ReplaceBookmarkContent(part, true, true);//用新添加段落的内容替换掉原书签的内容并保留格式 //移除sectiondocument.Sections.Remove(sec);//保存文档并打开document.SaveToFile("替换书签.docx");System.Diagnostics.Process.Start("替换书签.docx");}} }
测试结果:
以上是本次关于C# 操作Word书签功能的补充介绍,如需转载,请注明出处。
(本文完)