How to automate Microsoft word 2003 from WPF?

2019-05-11 08:14发布

问题:

I have a WPF window( using c# as code behind) that has some text fields.
What I want is, when the user presses the print button I want to take the information on these fields and use Microsoft word 2003 template. The template has some blank fields to be filled with these info coming from WPF widow.
How would I automate word to do this?

回答1:

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}" />


回答2:

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.