I have a WPF window( using c# as code behind) that has some text fields, and I want when the user press print button take the information on these fields and use Microsoft word 2003 template that has some blank fields to be filled with these info coming from WPF widow. How would I automate word to do this?
This is easy:
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.
Create a Word.Application application object
var app = new Word.Application()
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.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}" />
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:
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.