[英]C# Word Interop - “Find and replace” finds word but does not replace it
下面的代碼能夠找到我要查找的文本,但是當我替換它時,該文本不會被替換。 我沒有例外。
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();
要測試代碼:
將以下內容粘貼到其中:
([標簽名] [標簽名])
地址編號:2
堆棧溢出
擁有這輛rad汽車的教皇被命名([Tag FirstName],[Tag LastName])
該文檔使用此示例進行替換
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);
}
您會注意到它聲明了replaceAll = Word.WdReplace.wdReplaceAll
,然后將其傳遞到findObject.Execute
而您傳遞的WdReplace.wdReplaceOne
將僅替換找到的第一項。
代碼工作正常,我將表單字段和普通文本混合在一起,而ms-word提供的“查找和替換”功能無法完全解決該問題(再次可以找到但不能替換)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.