1

https://docs.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-search-for-and-replace-text-in-documents?view=vs-2019

微软没有在文档中给出完整的代码。但是有了这个我的代码尝试下面的文本没有被替换。出了什么问题以及如何将替换的内容保存到名为的文件中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();
        }

    }
}
4

1 回答 1

0

我认为您有缺少定义的问题,我添加了保存方法:

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;
    }

  }
}
于 2020-03-31T13:38:18.590 回答