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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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:
This assumes your data context class has a DependencyProperty "LastName" that is bound from the XAML like this:
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:
This is because all method parameters are 'ref' parameters, so you can't pass the usual constants,
null
,true
, andfalse
.Automation Samples Using Managed Code (Visual Basic or Visual C#)
A comprehensive list of automation samples.