【发布时间】:2013-09-14 14:28:20
【问题描述】:
我想做的是编写一个应用程序,它可以在 Microsoft Word 文档中查找和替换所有出现的给定字符串。
到目前为止,我选择使用 Microsoft.Office.Interop.Word 程序集。它有效,但不完全是我想要的。问题是它正在匹配子字符串并替换它们。
到目前为止,这是我的代码:
foreach (DataRow drCrossWalkItem in dtCrossWalk.Rows)
{
foreach (Word.Range myStoryRange in doc.StoryRanges)
{
myStoryRange.Find.MatchWholeWord = true;
myStoryRange.Find.MatchPrefix = false;
myStoryRange.Find.MatchSuffix = false;
myStoryRange.Find.Text = drCrossWalkItem["strOldValue"].ToString();
myStoryRange.Find.Replacement.Text = drCrossWalkItem["strNewValue"].ToString();
myStoryRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;
myStoryRange.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);
}
}
doc.SaveAs2(strFinalPath);
doc.Close(ref missing, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc);
所以它在大多数情况下都能完美运行,但我遇到的问题是在以下示例中:
Document Text:
test_item_one
test_item_one_two_three
假设我想用“hello”替换“test_item_one”——在我当前的程序中,它会像这样替换两行:
Document Text:
hello
hello_two_three
显然匹配“整个单词”不包括_。这就像您在 Microsoft Word 中尝试查找/替换一样。知道是否有其他选项可以解决此特定情况吗?
【问题讨论】:
-
我已经删除了我的答案,因为我认为你的态度非常不尊重和不值得帮助。不要指望我提供更多帮助。
标签: c# replace ms-word find interop