Click here to Skip to main content
13,193,056 members (82,314 online)
Click here to Skip to main content
Add your own
alternative version


299 bookmarked
Posted 14 Apr 2003

Microsoft Word Documents from ASP.NET

, 3 Jun 2003
Rate this:
Please Sign up or sign in to vote.
Creating and opening Microsoft Word documents from ASP.NET


This article is being written in response of the need of building Microsoft Word document in an ASP.NET project. This article demonstrates how to create and modify document using Microsoft Word with ASP.NET.


Automation is a process that allows applications that are written in languages such as Visual Basic .NET or C# to programmatically control other applications. Automation to Word allows you to perform actions such as creating new documents, adding text to documents, mail merge, and formatting documents. With Word and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using automation. Word exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Word. For example, there is an Application object, a Document object, and a Paragraph object, each of which contain the functionality of those components in Word.

The project

The first step in manipulating Word in .NET is that you'll need to add a COM reference to your project by right clicking in the solution explorer on References->Add Reference. Click on the COM tab and look for the Microsoft Word 10.0 Object Library. Click Select and OK.

Add Com Reference

This will automatically place an assembly in your application directory that wraps COM access to Word.

Now you can instantiate an instance of a Word application:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();

You can call the interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word. The best way to learn how to navigate the object models of Word, Excel, and PowerPoint is to use the Macro Recorder in these Office applications:

  1. Choose Record New Macro from the Macro option on the Tools menu and execute the task you're interested in.
  2. Choose Stop Recording from the Macro option on the Tools menu.
  3. Once you are done recording, choose Macros from the Macro option on the Tools menu, select the macro you recorded, then click Edit.

This takes you to the generated VBA code that accomplishes the task you recorded. Keep in mind that the recorded macro will not be the best possible code in most cases, but it provides a quick and usable example.

For example to open an existing file and append some text:

object fileName = "c:\\database\\test.doc";
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
Word.ApplicationClass oWordApp = new Word.ApplicationClass();

Word.Document oWordDoc = oWordApp.Documents.Open(ref fileName, 
                            ref missing,ref readOnly, 
                            ref missing, ref missing, ref missing, 
                            ref missing, ref missing, ref missing, 
                            ref missing, ref missing, ref isVisible, 
                            ref missing,ref missing,ref missing);


oWordApp.Selection.TypeText("This is the text");

oWordApp.Application.Quit(ref missing, ref missing, ref missing);

Or to open a new document and save it:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();

Word.Document oWordDoc = oWordApp.Documents.Add(ref missing, 
                           ref missing,ref missing, ref missing);


oWordApp.Selection.TypeText("This is the text");

oWordApp.Application.Quit(ref missing, ref missing, ref missing);

In C#, the Word Document class's Open method signature is defined as Open(ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object). What this means is that in C# the Open method takes 15 required arguments, and each argument must be preceded with the ref keyword and each argument must be of type object. Since the first argument is a file name, normally a String value in Visual Basic. NET, we must declare a variable of type object that holds the C# string value, hence the code:

object fileName = "c:\\database\\test.doc";

Although we only need to use the first argument in the Open method, remember that C# does not allow optional arguments, so we provide the final 14 arguments as variables of type object that hold values of System.Reflection.Missing.Value

Use a template

If you are using automation to build documents that are all in a common format, you can benefit from starting the process with a new document that is based on a preformatted template. Using a template with your Word automation client has two significant advantages over building a document from nothing:

  • You can have greater control over the formatting and placement of objects throughout your documents.
  • You can build your documents with less code.

By using a template, you can fine-tune the placement of tables, paragraphs, and other objects within the document, as well as include formatting on those objects. By using automation, you can create a new document based on your template with code such as the following:

Word.ApplicationClass oWordApp = new Word.ApplicationClass();
object oTemplate = "c:\\";
oWordDoc = oWordApp.Documents.Add(ref oTemplate, 
              ref Missing,ref Missing, ref Missing);

In your template, you can define bookmarks so that your automation client can fill in variable text at a specific location in the document, as follows:

object oBookMark = "MyBookmark";
oWordDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

Another advantage to using a template is that you can create and store formatting styles that you wish to apply at run time, as follows:

object oStyleName = "MyStyle";
oWordDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

Using the class CCWordApp

The project contains a file: CCWordApp.cs. I didn't want to write every time all the code necessary to insert text, open a file, etc...So I decided to write a class CCWordApp that wraps the most important function. This is a brief description of the class and its functions.

public class CCWordApp 
    //it's a reference to the COM object of Microsoft Word Application 
    private Word.ApplicationClass oWordApplic;    
    // it's a reference to the document in use 
    private Word.Document oWordDoc;                    
    // Activate the interface with the COM object of Microsoft Word 
    public CCWordApp();
    // Open an existing file or open a new file based on a template 
    public void Open( string strFileName);

    // Open a new document
    public void Open( );

    // Deactivate the interface with the COM object of Microsoft Word 
    public void Quit( );

    // Save the document
    public void Save( );
    //Save the document with a new name as HTML document 
    public void SaveAs(string strFileName );

    // Save the document in HTML format
    public void SaveAsHtml(string strFileName );

    // Insert Text
    public void InsertText( string strText);

    // Insert Line Break
    public void InsertLineBreak( );
    // Insert multiple Line Break
    public void InsertLineBreak( int nline);

    // Set the paragraph alignment
    // Possible values of strType :"Centre", "Right", "Left", "Justify"
    public void SetAlignment(string strType );

    // Set the font style
    // Possible values of strType :"Bold","Italic,"Underlined"
    public void SetFont( string strType );
    // Disable all the style 
    public void SetFont( );

    // Set the font name
    public void SetFontName( string strType );

    // Set the font dimension
    public void SetFontSize( int nSize );

    // Insert a page break
    public void InsertPagebreak();

    // Go to a predefined bookmark
    public void GotoBookMark( string strBookMarkName);

    // Go to the end of document
    public void GoToTheEnd( );

    // Go to the beginning of document
    public void GoToTheBeginning( );

So the code to open an existing file will be:

CCWordApp test ;
test = new CCWordApp();
test.Open ("c:\\database\\test.doc");
test.InsertText("This is the text");
test.Save ();


The demo project contains:

  • CCWordApp.cs - the class
  • CreateDocModel.aspx: an example of building a new document based on a template and the use of bookmarks
  • CreateNewDoc.aspx: an example of building a new document and inserting some text
  • ModifyDocument.aspx: an example of opening an existing document and appending some text at the end
  • template\ an example of a template (used in CreateDocModel.aspx)

Keep in mind that the directory ,in which you save the files, must be writeable. Please check the Web.config to change the path.



This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
Italy Italy
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralRe: SaveAs exception "Word cannot save this file because it is already open elsewhere" Pin
cwienands25-Mar-08 14:37
membercwienands25-Mar-08 14:37 
QuestionProblem with this component. Pin
Member 234763821-Dec-07 5:53
memberMember 234763821-Dec-07 5:53 
AnswerRe: Problem with this component. Pin
Member 115487821-Jun-10 3:55
memberMember 115487821-Jun-10 3:55 
GeneralProblem with oWordDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here" [modified] Pin
AVMilenko30-Nov-07 10:48
memberAVMilenko30-Nov-07 10:48 
QuestionProblem with Open Method Pin
Mehdi Mokhtari24-Nov-07 19:14
memberMehdi Mokhtari24-Nov-07 19:14 
QuestionAny Solution to "Access Denied" ? Pin
Chintan Jariwala24-Aug-07 21:20
memberChintan Jariwala24-Aug-07 21:20 
AnswerRe: Any Solution to "Access Denied" ? Pin
joemag13-Sep-07 4:30
memberjoemag13-Sep-07 4:30 
AnswerRe: Any Solution to "Access Denied" ? Pin
Mahendra Kumar Srivastava16-Feb-09 23:03
memberMahendra Kumar Srivastava16-Feb-09 23:03 
Try to add following key in the registry if you have tried the above steps and still failing. Save below text as .reg file and double click to add it to registry. You can also alternatively create an entry if it does not exists.



QuestionReading text from Word Application Pin
khan_SharePoint23-Aug-07 23:06
memberkhan_SharePoint23-Aug-07 23:06 
GeneralProblems with windows services Pin
kelphis22-Aug-07 5:19
memberkelphis22-Aug-07 5:19 
GeneralRe: Problems with windows services Pin
joemag13-Sep-07 4:36
memberjoemag13-Sep-07 4:36 
Questionerror while running this code Pin
ruchiricki20-Aug-07 20:01
memberruchiricki20-Aug-07 20:01 
GeneralOutput Data to Microsoft Words document from ASP.NET Pin
TeeLeong20-Aug-07 13:37
memberTeeLeong20-Aug-07 13:37 
Questionword object in asp Pin
simplegoel20-Aug-07 2:36
membersimplegoel20-Aug-07 2:36 
GeneralDocuments.Add returning null Pin
shirtlesswonder29-Jun-07 4:10
membershirtlesswonder29-Jun-07 4:10 
GeneralSplit one RTF file to Multiple RTF file Pin
AminSh28-Jun-07 23:34
memberAminSh28-Jun-07 23:34 
QuestionComplier error [modified] Pin
Kumputed27-Feb-07 10:16
memberKumputed27-Feb-07 10:16 
GeneralSignature Pin
Victor M. Bello A.6-Feb-07 11:51
memberVictor M. Bello A.6-Feb-07 11:51 
QuestionHow to copy the text formatting too Pin
spiro_razboinika28-Jan-07 5:44
memberspiro_razboinika28-Jan-07 5:44 
GeneralGood Article But............................ Pin
cykophysh3910-Nov-06 1:02
membercykophysh3910-Nov-06 1:02 
GeneralRe: Good Article But............................ Pin
joemag13-Sep-07 4:33
memberjoemag13-Sep-07 4:33 
Question'The server threw an exception Pin
vivekdeshpande25-Sep-06 23:37
membervivekdeshpande25-Sep-06 23:37 
QuestionRe: 'The server threw an exception Pin
Kumputed27-Feb-07 10:15
memberKumputed27-Feb-07 10:15 
QuestionOpen a word file that is set a password. Pin
CongSong18-Sep-06 17:24
memberCongSong18-Sep-06 17:24 
GeneralI can not run it when i set HomeDirectory Pin
superdragon31-Aug-06 19:07
membersuperdragon31-Aug-06 19:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171017.2 | Last Updated 4 Jun 2003
Article Copyright 2003 by Michela
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid