How to automate Microsoft word 2003 from WPF?

こ雲淡風輕ζ 提交于 2019-12-06 01:24:31

This is easy:

  1. Add a COM reference to the the "Microsoft Word 11.0 Object Library" (or use the Microsoft.Office.Interop.Word assembly). You may have to in install Visual Studio Tools for Office System and/or browse to your the Primary Interop Assembly, depending on your VS.NET and Office versions and what else you have installed.

  2. Create a Word.Application application object var app = new Word.Application()

  3. Open the document with var doc = app.Documents.Open(...). Note that in C# 3.5 or below you must pass all parameters. You can use a variable initialized to System.Reflection.Missing.Value for most of them.

  4. Iterate through doc.Fields using foreach: Read and parse the field's .Code range, then update the field's .Result range based on the text box content.

For example:

foreach(Field f in doc.Fields)
  if(f.Code.Text.Contains("lastName"))
    f.Result.Text = this.LastName;
  ...

This assumes your data context class has a DependencyProperty "LastName" that is bound from the XAML like this:

<TextBox Text="{Binding LastName}" />
ProfK

That you are doing this from a WPF window is immaterial. The code behind should do all the automation. Below are some resources that may help you with guidance or examples:

Please note that it is not advisable to do this on a server. I know your requirement is for Wpf, but that may end up getting involved in a Silverlight project.

BTW: Using the COM objects is a little trickier than normal .NET objects, and the Office COM objects even more so:

Word Automation using C#

Note his initial declaration:

Object oMissing = System.Reflection.Missing.Value()
Object oTrue = true;
Object oFalse = false;

This is because all method parameters are 'ref' parameters, so you can't pass the usual constants, null, true, and false.

Automation Samples Using Managed Code (Visual Basic or Visual C#)

A comprehensive list of automation samples.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!