您可以使用以下代码打开 Word 文档并突出显示搜索到的文本:
private void btnFind_Click(object sender, EventArgs e)
{
object fileName = "xxxxx"; //The filepath goes here
string textToFind = "xxxxx"; //The text to find goes here
Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
object missing = System.Type.Missing;
try
{
doc = word.Documents.Open(ref fileName, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
doc.Activate();
foreach (Word.Range docRange in doc.Words)
{
if(docRange.Text.Trim().Equals(textToFind,
StringComparison.CurrentCultureIgnoreCase))
{
docRange.HighlightColorIndex =
Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
docRange.Font.ColorIndex =
Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
您必须使用以下语句添加对 Microsoft.Office.Interop.Word 的引用:
using Word = Microsoft.Office.Interop.Word;
如果你想做一个函数,然后修改它