In this post i will show you how to create a simple word document with the COM library. For this you will need MS Word installed on your computer in order to get it work.
First we need to add a reference to the project: right-click project -> add reference -> COM -> Microsoft Word 12.0 Object Library -> Add
Earlier versions should work also, i have Office 2007 installed so i have the 12.0 library. If you want to create documents which work on Office 97 then get an earlier library.
First we add a reference to the class:
using Microsoft.Office.Interop.Word;
Then in our function we create the document:
{
object fileName = "D:\\helloworld.doc";
object novalue = Missing.Value;
ApplicationClass objWord = new ApplicationClass();
Document objWordDoc = objWord.Documents.Add(ref novalue, ref novalue, ref novalue, ref novalue);
objWordDoc.Activate();
object start = 0;
object end = 0;
Range myRange = objWordDoc.Range(ref start, ref end);
myRange.InsertParagraphBefore();
myRange.InsertBefore("Hello world");
//Add shading
myRange.Shading.BackgroundPatternColor = WdColor.wdColorLightOrange;
myRange.Font.Name = "Arial";
myRange.Font.Size = 18;
myRange.ParagraphFormat.SpaceAfter = 0;
//Next paragraph style, first set the range.
myRange.SetRange(myRange.End, myRange.End);
myRange.InsertParagraphBefore();
myRange.InsertBefore("Hello world2");
myRange.InsertParagraphAfter();
//Remove shading
myRange.Shading.BackgroundPatternColorIndex = WdColorIndex.wdAuto;
myRange.Font.Name = "Arial";
myRange.Font.Size = 14;
myRange.ParagraphFormat.SpaceAfter = 0;
objWordDoc.SaveAs(ref fileName, ref novalue, ref novalue, ref novalue,
ref novalue, ref novalue, ref novalue, ref novalue, ref novalue,
ref novalue, ref novalue, ref novalue, ref novalue, ref novalue,
ref novalue, ref novalue); //Parameters can be different to older Word library's
objWord.Quit(ref novalue, ref novalue, ref novalue);
}
All the functions in word are available in the library but there's a LOT and i mean really a lot!
Here are some links which can come handy:
http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx?MessageChildID=4167&Delete=true
http://support.microsoft.com/kb/316384
Goodluck creating word documents.