替换 Word Interop 16 中的文本
Replace text in Word Interop 16
Microsoft 未在文档中提供完整代码。但是有了这个我的代码尝试下面的文本没有被替换。出了什么问题以及如何将替换的内容保存到名为 Word2.docx
的文件中?
using Microsoft.Office.Interop.Word;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SearchReplace();
}
private static object missing; // <- Is this correct ?
private static void SearchReplace()
{
Application application = new Application();
application.Documents.Add("C:\Users\test\Desktop\word.docx");
Microsoft.Office.Interop.Word.Find findObject = application.Selection.Find;
findObject.ClearFormatting();
findObject.Text = "find me";
findObject.Replacement.ClearFormatting();
findObject.Replacement.Text = "Found";
object replaceAll = Microsoft.Office.Interop.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);
application.Documents.Save();
}
}
}
我认为您对缺少定义有疑问,我已经添加了保存方法:
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SearchReplace();
}
private static void SearchReplace()
{
object missing = System.Reflection.Missing.Value;
Application application = new Application();
Microsoft.Office.Interop.Word.Document document = application.Documents.Add("C:\Users\test\Desktop\word.docx");
Microsoft.Office.Interop.Word.Find findObject = application.Selection.Find;
findObject.ClearFormatting();
findObject.Text = "find me";
findObject.Replacement.ClearFormatting();
findObject.Replacement.Text = "Found";
object replaceAll = Microsoft.Office.Interop.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);
object filename = "C:\savefile.docx";
document.SaveAs2(ref filename);;
document.Close(ref missing, ref missing, ref missing);
document = null;
application.Quit(ref missing, ref missing, ref missing);
application = null;
}
}
}