Click here to Skip to main content
16,020,568 members
Articles / Web Development / ASP.NET
Article

Microsoft Word Documents from ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.69/5 (93 votes)
3 Jun 20035 min read 2.4M   33.6K   298   356
Creating and opening Microsoft Word documents from ASP.NET

Introduction

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.

Background

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:

C#
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:

C#
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);

oWordDoc.Activate();

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

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);

oWordDoc.Activate();

oWordApp.Selection.TypeText("This is the text");
oWordApp.Selection.TypeParagraph();
oWordDoc.SaveAs("c:\\myfile.doc");

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:

C#
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:

C#
Word.ApplicationClass oWordApp = new Word.ApplicationClass();
object oTemplate = "c:\\MyTemplate.dot";
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:

C#
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:

C#
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.

C#
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:

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

Details

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\template1.dot: 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.

References

License

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


Written By
Web Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestioncreate a word document in asp net using c# Pin
Antony Bruno1-Feb-19 21:24
Antony Bruno1-Feb-19 21:24 
Questionmerge some parts Pin
kodemax11-Jan-15 19:36
kodemax11-Jan-15 19:36 
QuestionMessage Closed Pin
12-Jun-14 4:15
Robert te Kaat12-Jun-14 4:15 
AnswerRe: Word automation on a server is a no go Pin
PIEBALDconsult12-Jun-14 4:56
mvePIEBALDconsult12-Jun-14 4:56 
Questionthanks for this program Pin
joginder-banger29-Oct-13 1:37
professionaljoginder-banger29-Oct-13 1:37 
QuestionRetrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. Pin
Dardan Shabani6-Aug-13 12:19
Dardan Shabani6-Aug-13 12:19 
AnswerRe: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. Pin
Member 98239034-Mar-14 1:15
Member 98239034-Mar-14 1:15 
AnswerRe: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. Pin
Hrishikesh Shivacharan27-Apr-15 2:03
Hrishikesh Shivacharan27-Apr-15 2:03 
QuestionHow to disable the Promt message while opening the document uinsg the open method Pin
tarun0019715-Apr-13 0:01
tarun0019715-Apr-13 0:01 
GeneralMy vote of 3 Pin
wangerpang5-Mar-13 1:48
wangerpang5-Mar-13 1:48 
Questionthis programs can not work on the release version Pin
wangerpang5-Mar-13 1:48
wangerpang5-Mar-13 1:48 
GeneralMy vote of 1 Pin
vinayakJJ23-Dec-12 22:08
vinayakJJ23-Dec-12 22:08 
QuestionOpen word document from oracle database in vb.net 2008 Pin
BLVRS16-Jul-12 2:27
BLVRS16-Jul-12 2:27 
QuestionMessage Closed Pin
22-Dec-11 11:35
Jure.L22-Dec-11 11:35 
AnswerRe: A much better solution Pin
siegeon13-Sep-12 6:59
siegeon13-Sep-12 6:59 
Questionproblem with language settings Pin
bilgicbabam29-Sep-11 7:57
bilgicbabam29-Sep-11 7:57 
GeneralSaveAs .docx Pin
kraazee16-Jun-11 2:41
kraazee16-Jun-11 2:41 
GeneralRe: SaveAs .docx Pin
Robert Hutch15-Feb-12 0:47
Robert Hutch15-Feb-12 0:47 
GeneralAdd image at Header and footer contail page number and table Pin
shrishail39-Feb-11 20:47
shrishail39-Feb-11 20:47 
GeneralCouldn't work on anther machine Pin
Member 36244896-Dec-10 13:52
Member 36244896-Dec-10 13:52 
GeneralIIS7 Not working Pin
Jas Fowler18-Apr-10 16:43
Jas Fowler18-Apr-10 16:43 
GeneralRe: IIS7 Not working Pin
tjebbour4-Jun-10 20:13
tjebbour4-Jun-10 20:13 
GeneralProcesses are still working! Pin
User 568914316-Apr-10 10:17
User 568914316-Apr-10 10:17 
Generalhi Pin
Mico Perez12-Mar-10 18:10
Mico Perez12-Mar-10 18:10 
GeneralMy vote of 2 Pin
Ramesh Babu Sivaraju3-Feb-10 2:43
Ramesh Babu Sivaraju3-Feb-10 2:43 

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.