如何在word doc中使用C#进行查找和替换?例如,让我们替换单词" Run"的所有实例。与" Ran"?
也许像String.Replace(" run"," ran");但执行得很好,但没有做出任何改变。
答案 0 :(得分:0)
查找和替换方法:
public void FindAndReplaceWordText(ref Microsoft.Office.Interop.Word.Document wordDoc, string textToReplace, string newText)
{
object missing = System.Type.Missing;
foreach (Microsoft.Office.Interop.Word.Range tmpRange in wordDoc.StoryRanges)
{
//set the text to find and replace
tmpRange.Find.Text = textToReplace;
tmpRange.Find.Replacement.Text = newText;
tmpRange.Find.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
//Declare an object to pass as a parameter that sets the Replace parameter to the "wdReplaceOne" enum.
object replaceOne = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
//Execute the Find and Replace
tmpRange.Find.Execute(ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref replaceOne,
ref missing, ref missing, ref missing, ref missing);
}
调用方法:
FindAndReplaceWordText(ref wordDoc, "Ran", "Run");
希望这有帮助!