C#Microsoft.Office.Interop.Word用Selection.Find.Execute()替换第一个单词

时间:2017-06-16 17:58:37

标签: c# ms-word

我尝试使用Microsoft.Office.Interop.Word在C#中创建报表。我有一个模板和一些我想要替换的不同的单词。但如果我使用

> Selection.Find.Execute()

它只替换第一个单词。 我的代码:

 Word.Application app = new Word.Application();
            Word.Document doc = null;

            object template = "ReportTest.dotx";
            object toFile = "ReportFinish.doc";

            object missing = System.Reflection.Missing.Value;

            doc = app.Documents.Open(template, missing, missing);
            app.Selection.Find.ClearFormatting();
            app.Selection.Find.Replacement.ClearFormatting();

            app.Selection.Find.Execute("[organisation]", missing, missing, missing, missing, missing, missing, missing,
                missing, "Firedepartment");
            app.Selection.Find.Execute("[trainer]", missing, missing, missing, missing, missing, missing, missing,
                missing, "John Silver");

            app.Selection.Find.Execute("[trainee]", missing, missing, missing, missing, missing, missing, missing,
                missing, "Smith");

            object Save = (object) toFile;
            doc.SaveAs(Save,missing,missing,missing);

            doc.Close(false,missing,missing);
            app.Quit(false,false,false);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

因此,如果它找到了组织,它就用Firedepartment取而代之,但另一个却没有改变。那么有没有办法替换所有不同的单词?

word-template看起来像:

Department: [organisation] 
Trainer: [trainer] 
Trainee: [trainee]`

完成文档应如下所示: 部门:消防部门 培训师:John Silver 实习生:史密斯

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使用IPEndPoint ep = new IPEndPoint (new IPAddress (new byte []{ 127, 0, 0, 1 }), 9042); var socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); var connectTimeoutMs = 50; var connectTask = Task.Factory.FromAsync( (ipEndPoint, callback, state) => ((Socket)state).BeginConnect(ipEndPoint, callback, state), asyncResult => ((Socket)asyncResult.AsyncState).EndConnect(asyncResult), ep, socket); var timeoutTask = Task.WhenAny(connectTask, Task.Delay(Options.connectTimeoutMs)); if (await timeoutTask != connectTask) { throw new SocketException((int)SocketError.TimedOut); } await connectTask; 的文档说

Selection.Find

我会添加一个对

的调用
 When the item is found that matches the search criteria, it is automatically selected.

在第二次和第三次拨打app.Selection.Collapse(); 之前。