Spire.Doc为开发者提供了查找和替换功能的方法,我们可以通过document.FindString()方法查找文档中某一个特定词汇并对它进行高亮替换, 也可以通过document.FindAllString()方法查找文本中所有地该词汇对将找到的词汇使用Document.Replace()方法进行替换更改。本文将详细介绍如何使用C#来实现word查找,替换和高亮显示功能。
- //新建一个word文档对象并加载sample文档
- Document document = new Document();
- document.LoadFromFile("Test.docx", FileFormat.Docx2010);
-
- //查找一个特定字符串 ”Spire.Doc”
- TextSelection selection = document.FindString("Spire.Doc", false, true);
- TextRange range = selection.GetAsOneRange();
-
- //替换字符串
- range.Text = "Replaced Text";
-
- //设置高亮颜色
- range.CharacterFormat.HighlightColor = Color.Yellow;
-
- //查找文档中所有字符串 ”Microsoft”
- TextSelection[] text = document.FindAllString("Microsoft", false, true);
-
- //设置高亮颜色
- foreach (TextSelection seletion in text)
- {
- seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green;
- }
-
- //使用 ”MS” 替换所有 ”Microsoft”
- document.Replace("Microsoft", "MS", false, true);
-
- //保存文档
- document.SaveToFile("Result.docx", FileFormat.Docx2010);复制代码