Creating a Word document using ASP.NET and C#
[tweetmeme style=”compact”]In one of my projects recently, I had to create word documents dynamically using ASP.NET. I turned to MSDN for help and was surprised to find how easy it was to do so.
I am using Visual Studio 2002 and .NET Framework 1.0. Therefore if you are using the latest versions, unlike me 😦 then do check out for the updates in the classes and methods that I am going to use in this article.
1) OK, lets start. Open up Visual Studio and create an ASP.NET Web application using C#.
2) Now we have to add a COM reference to our project. In the references dialog box, under COM you will find Microsoft Word 9.0 Object Library. Select it and add it to the project. This will add few COM dll’s in the bin directory.
3) Now the code…
object fileName="D:\\MyWord.doc"; object novalue=System.Reflection.Missing.Value; Word.ApplicationClass objWord = new Word.ApplicationClass(); Word.Document objWordDoc=objWord.Documents.Add(ref novalue, ref novalue, ref novalue, ref novalue); objWordDoc.Activate(); objWord.Selection.TypeText(".NET Rocks!!!"); objWord.Selection.TypeParagraph(); objWord.Selection.TypeText("Savage loves .NET"); objWordDoc.SaveAs(ref fileName, ref novalue, ref novalue, ref novalue, ref novalue, ref novalue, ref novalue, ref novalue, ref novalue, ref novalue, ref novalue); objWord.Quit(ref novalue, ref novalue, ref novalue);
Now check the MyWord.doc file in the D: drive.
The code is pretty simple and intuitive, hence a quick explanation.
* We are first creating a object of Word.ApplicationClass
* Next we add a Word document to this object. Incase you don’t want to pass a particular parameter, use the ‘novalue’ object that we have created in the code.
* The following steps are pretty self explanatory.
The Visual Studios’ Intellisense feature will let us know of the expected parameters of each method. In the latest versions of .NET framework the number of parameters required is more.
Do check out http://msdn.microsoft.comto learn about automation in .NET