Windows Office Application Interface

You can use C# to manipulate Microsoft Office programs such as Word and Excel. You can open, create, edit and do essentially everything you can do in the programs natively using instead C# (albeit a little longer…) and libraries provided by Microsoft.

A good tutorial on the Word API can be found here in the MSDN library.

Tutorial

 To create a word application (the first steps no matter what your doing) is to add the Microsoft Word x.x Object Library reference to your C# project. Right click on your project in the solution explorer, click ‘Add Reference’, click the ‘COM’ tab, and then select Microsoft Word x.x Object Library from the list as shown in the picture. Click ‘OK’ to add it to your project. Note that I was using Microsoft Office 2010 and the Microsoft Word 14.0 Object Library when writing this tutorial, so features/processes could be slightly different for other versions.

Now that the reference has been added, add the following use code to make typing easier

Now create a new word application object. This is the equivalent to starting up Microsoft Word.

You can choose to make it visible to the user by setting the property

To create a new document inside the application (usually the second step), call the method

At this point you can start playing around with the document by adding text, pictures, objects (such as textboxes, rectangles, e.t.c). See below for some hints. All hints assume you have instantiated the Word application and at least one document inside it.

Text Boxes:

To create a textbox:

To change weather or not you can see the text box border modify the property:

To insert text into the textbox modify the peoperty

To change the font size

To change the font colour

To change the alignment of the text

To modify the margins of the textbox modify the properties

Tables

Create a table using the method

Manipulating The Cursor

Manipulating the cursor is done with the methods and parameters in the class

Selection is just another name for ‘current cursor position’.

To jump to the last line in a document, use the method

To insert a break (e.g. line, page) at the current cursor position, use the method

Breaks (Line, Page, …)

To insert a break at the current selection point, call the following method:

Posted: January 8th, 2012 at 4:37 pm