C# 操作Word书签(二)——读取、替换Word书签
2021-03-28 11:29
标签:studio count fbo .text bookmark ref rap from += 原文档中的书签内容: 【C#】 读取结果如下: 【C#】 测试结果: 以上是本次关于C# 操作Word书签功能的补充介绍,如需转载,请注明出处。 C# 操作Word书签(二)——读取、替换Word书签 标签:studio count fbo .text bookmark ref rap from += 原文地址:http://blog.51cto.com/eiceblue/2147149
工具使用
示例代码
1. 读取word书签
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、替换书签内容
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();//添加section
sec.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和TextBodyPart
TextBodySelection 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);//用新添加段落的内容替换掉原书签的内容并保留格式
//移除section
document.Sections.Remove(sec);
//保存文档并打开
document.SaveToFile("替换书签.docx");
System.Diagnostics.Process.Start("替换书签.docx");
}
}
}
(本文完)
文章标题:C# 操作Word书签(二)——读取、替换Word书签
文章链接:http://soscw.com/index.php/essay/69034.html