C#Word Interop - “查找和替换”查找单词但不替换它

时间:2017-06-15 09:20:18

标签: c# replace ms-word find interop

以下代码能够找到我正在寻找的文本,但是当我去替换它时,文本不会被替换。我没有例外。

var word = new Application();
File.Delete(@"Your new test document.docx");
File.Copy(@"Your test document.docx", @"Your new test document.docx");
var document = word.Documents.Open(@"Your new test document.docx");
document.Activate();

while (document.Content.Find.Execute(FindText: "([Tag"))
{
    var stringToReplace = document.Content.Text.Substring(document.Content.Text.IndexOf("([Tag"), document.Content.Text.IndexOf("])") + 2 - document.Content.Text.IndexOf("([Tag"));
    var replacement = stringToReplace.Replace("(", "").Replace(")", "");

    if (document.Content.Find.Execute(FindText: stringToReplace))
    {
        Console.WriteLine(stringToReplace);
        document.Content.Find.Execute(FindText: stringToReplace, ReplaceWith: replacement, Replace: WdReplace.wdReplaceOne);
    }
    else
        Console.WriteLine("Failed");
}

document.Close(true);
word.Quit();
Marshal.ReleaseComObject(document);
Marshal.ReleaseComObject(word);
Console.WriteLine("Done");
Console.ReadLine();

测试代码:

  1. 创建word文档。
  2. 将以下内容粘贴到其中:

    ([Tag FirstName] [Tag LastName])

    地址编号:2

    #1

    拥有该汽车的教皇被命名为([Tag FirstName],[Tag LastName])

  3. 在代码中保存并更新文件路径。

2 个答案:

答案 0 :(得分:0)

The documentation uses this example for replace

private void SearchReplace()
{
    Word.Find findObject = Application.Selection.Find;
    findObject.ClearFormatting();
    findObject.Text = "find me";
    findObject.Replacement.ClearFormatting();
    findObject.Replacement.Text = "Found";

    object replaceAll = Word.WdReplace.wdReplaceAll;
    findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}

You'll notice it declares replaceAll = Word.WdReplace.wdReplaceAll and then passes it into findObject.Execute whereas you pass WdReplace.wdReplaceOne in which will only replace the first item found.

答案 1 :(得分:0)

代码工作正常,我正在混合formfields和普通文本以及"查找和替换"功能ms-word提供无法完全使用它(再次能够找到它,但不能替换它)。