Friday, September 21, 2012

Word Tutorial

In this post I want to show, how to connect C# and Microsoft Office Word. I will show, how to create new Word documents using C#, insert texts, change settings, open documents, save and display them.
First we have to add the corresponding component to our project, which can be done via Project - Add Reference - COM - Microsoft Word xx Object Library. xx in that means the current version number.
Then we use the code using Word = Microsoft.Office.Interop.Word to be able to use the Word object under the name Word.


Create Word Instance and Show It:
Word.Application WordApp = new Word.Application();
WordApp.Visible = true;
With that a new instance of the Word object is created. With enabling the visibility, this is shown. Since no documents are loaded yet, simply the grey Word window is shown.

Create New Word Document:
The propety Documents of the instance contains opened documents, we can add documents to this enumeration e.g. by opening or creating new ones. To create a new document, the following command is needed:
Word.Document NewDocument = WordApp.Documents.Add();

Close Document:
For this the function Close() is responsible, which is called from the corresponding document, so with above example:
NewDocument.Close();

Open Existing Word Document:
Object oMissing = System.Reflection.Missing.Value;
Word.Document ExistingDocument = WordApp.Documents.Open("Filename", oMissing, true, oMissing, "Password");
All arguments except the first one are optional. The 3. says, whether the document is to be opened read-only (true if yes). The 5. is the optional password.
The argument oMissing with the value System.Reflection.Missing.Value is very practical, it always returns the default value of the current argument and therefore can always be used as a placeholder for unused arguments.

Insert Text:
WordApp.Selection.TypeText("Hallo Welt");
This code types the given text in the currently top most opened document in the Documents enumeration.

Set Formattings:
Also with the Selection property formattings can be taken. If these are done before a TypeText command, they are applied to the written text. All known formattings are available, as for example:
WordApp.Selection.Font.Size = 20;

Save Document:
A document can either be saved with the parameterless function Save() or SaveAs2(). The last version expects a save path.

Quit Word Instance:
WordApp.Quit();

No comments:

Post a Comment