Click here to Skip to main content
Click here to Skip to main content
Go to top

Automating MS Word Using Visual Studio .NET

, 18 Dec 2003
Rate this:
Please Sign up or sign in to vote.
This code will demonstrate how to automate and get content from a MS Word document

Introduction

One day you may be asked to write a parser that will have to parse a bunch of documents and break them down into a structured model and store them in a relational-database. And those documents will most likely be written in MS Word. And the sad part would be that they would not have any structure, they will not follow any standard and they will include OLE/embedded objects. I was assigned with such a task, and it was a very interesting experience for me.

Since this was my first such project, meaning automating MS Office application, I had to go and do a lot of reading about automation. The good news is that there is a bunch of stuff out there; the bad news is that all of them are written for VB or VBA developers. I couldn’t find anything for C++ developers. Long story short, I am writing this article to make things a little easier for someone else that might be assigned with a similar task.

The original code I worked on was written using Borland C++ Builder 5 Professional. This article is however, the C# version. By the way if you are interested in seeing the C++ version ask for it and I will post it. I encourage people to take a look at the C++ version sometime to start appreciate the simplicity of C#.

Background

No special background is necessary. Just have some hands on experience with C#.

Using the code

I am going to include some code that will allow you to understand how to get what you need from a Word document. It really doesn’t matter if you are making a console application or a Windows application. The steps and the code is the same. So you can go ahead and create new C# project. You may choose to create a Windows Application that way you can click some button.

Okay so once you create a new project, go ahead and right click on References in the Solution Explorer, and select Add Reference… When the Add Reference window comes up select the COM tab. This will list all Component Names which are available on your machine, since we are going to use MS Word, we will scroll down until we find: Microsoft Word 9.0 Object Library.

Note: Yours might be a different version depending on the version of Office installed on your machine. This is for MS Word 2000.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace sparser
{
  /// Summary description for Form1.
  public class frmParserMainUI : System.Windows.Forms.Form
  {
    /// User Interface Objects
    /// I have removed the user interface object, since 
    /// they have nothing to do with
    /// the actual code, and they take a lot of space.

    ...
    
    /// Required designer variable.
    private System.ComponentModel.Container components = null;
    private System.Windows.Forms.OpenFileDialog openFileDialog;
    
    ...

The following block create MS Word COM Object. This is the object which will be used to access WORD application functions. To see what functions are available you can do it either within Visual Studio .NET IDE or MS Word.

    /// MS Word COM Object
    /// This is where we create our WORD object
    private Word.ApplicationClass vk_word_app = new Word.ApplicationClass();
    
    ...

To view the functions from MS Word, launch Word, hold down the Alt key and press F11 [Alt+F11], this will give you the VBA window, once there press F1 to get the help window, and do a search for document object. This is the best source of documentation for available functions. However, the documents have been written for VBA, but at least you know what the function does and what kind of parameters it takes.

Alright the code continued...

    ...


    /// The main entry point for the application.
    [STAThread]
    static void Main() 
    {
      Application.Run(new frmParserMainUI());
    }

    /// Get source document. Open a FileDialog window for 
    /// user to select single/multiple files for
    /// parsing.
    private void butSourceDocument_Click(object sender, System.EventArgs e)
    {
      if( openFileDialog.ShowDialog() == DialogResult.OK )
      {
        object  fileName = openFileDialog.FileName;
        object  saveFile = fileName + "_Vk.doc";
        
        
        object  vk_read_only  = false;
        object  vk_visible  = true;
        object  vk_false    = false;
        object  vk_true    = true;
        object  vk_dynamic  = 2;
        
        object  vk_missing  = System.Reflection.Missing.Value;

        // Let make the word application visible
        vk_word_app.Visible = true;
        vk_word_app.Activate();

        // Let's open the document
        Word.Document vk_my_doc = vk_word_app.Documents.Open( 
          ref fileName, ref vk_missing, ref vk_read_only, 
              ref vk_missing, ref vk_missing,
          ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing,
          ref vk_missing, ref vk_missing, ref vk_visible );
               
               ...

Alright, so here the user is given a file open dialog where they can select a Word document. Notice that we save the filename as an object. This is because the functions that we use need reference to object.

So now we can use our Word object to start Word. This is achieved by the vk_word_app.Visible = true; and vk_word_app.Activate(); The first statement makes sure that the instance of Word is visible, and the second one activate it. If you don't want the Word instance to be visible just set the Visible property to false.

Next we create a Word Document object, and that is done using Word.Document vk_my_doc = vk_word_app.Documents.Open( ... ); Notice all the parameters which are required by the function. Most of them are NULL values, so we use vk_missing which is a System.Reflection.Missing.Value.

So now we have created a Word instance and opened a Word document. Now let's move on with the code...

    ...

        // Let's create a new document
        Word.Document vk_new_doc = vk_word_app.Documents.Add( 
        ref vk_missing, ref vk_missing, ref vk_missing, ref vk_visible );

        // Select and Copy from the original document
        vk_my_doc.Select();
        vk_word_app.Selection.Copy();

        // Paste into new document as unformatted text
        vk_new_doc.Select();
        vk_word_app.Selection.PasteSpecial( ref vk_missing, ref vk_false,
          ref vk_missing, ref vk_false, ref vk_dynamic, 
          ref vk_missing, ref vk_missing );

        // close the original document
        vk_my_doc.Close( ref vk_false, ref vk_missing, ref vk_missing );
    ...

Next we would like to create a new document. This is just like clicking the New Blank Document button on the toolbar. So we create another Word Document object, and this time notice that we use vk_word_app.Documents.Add( ... ); This will add a new blank document which is also visible.

Next what we do is select all content from the document which we opened, and we copy it.

Next we paste our content into the new document with a special format. The format used in the code is for plain text. This is because we want to get rid of the crap Word puts into the formatting of the text. Then we close our original document without making any changes.

    ...

        vk_new_doc.Select();
        FindAndReplace( "^t^t^t^t^t^t^t", "^t", vk_num );

        // Save the new document
        vk_new_doc.SaveAs( ref saveFile, ref vk_missing, 
          ref vk_missing, ref vk_missing, ref vk_missing,
          ref vk_missing, ref vk_missing, ref vk_missing, 
          ref vk_missing, ref vk_missing, ref vk_missing );

        // close the new document
        vk_new_doc.Close( ref vk_false, ref vk_missing, ref vk_missing );

        // close word application
        vk_word_app.Quit( ref vk_false, ref vk_missing, ref vk_missing );
      }
    }

    ...

Now let's say if we are interested in doing a find and replace operation, we would basically select the whole document and use the Find and Replace function.

Note: The FindAndReplace function does not belong to Word object or Document object, it is user defined, the actual Find and Replace function is define in the following block.

Next we want to save our changes to the new document and close it.

And finally quit word.

    ...

    private void FindAndReplace( object vk_find, object vk_replace, 
       object vk_num )
    {
      object  vk_read_only  = false;
      object  vk_visible    = true;
      object  vk_false      = false;
      object  vk_true      = true;
      object  vk_dynamic    = 2;

      vk_word_app.Selection.Find.Execute( ref vk_find, 
        ref vk_false, ref vk_false,
        ref vk_false, ref vk_false, ref vk_false, ref vk_true, 
        ref vk_num, ref vk_false,
        ref vk_replace, ref vk_dynamic, ref vk_false, 
        ref vk_false, ref vk_false, ref vk_false );
    }
  }
}

The above block shows the actual FindAndReplace function. Notice that it belongs to the vk_word_app object. And the function operates on the active selection. The Find and Replace function is a part of the Find function with special parameters. These parameters can be identified in the documentation as I mentioned at the top of the article.

The code demonstrated above, illustrates how to open a word document, how to create a new word document, selecting, copying, pasting, and doing a Find and Replace function.

As you can see, once you get an understanding of how Word operates and go through the documentation you will be able to automate all the functions that Word has to provide.

        // Let's get the content from the document
        Word.Paragraphs vk_my_doc_p = vk_new_doc.Paragraphs;
        // Count number of paragraphs in the file
        long p_count = vk_my_doc_p.Count;
        // step through the paragraphs
        for( int i=1; i<=p_count; i++ )
        {
          Word.Paragraph vk_p = vk_my_doc_p.Item( i );
          Word.Range vk_r = vk_p.Range;
          string text = vk_r.Text;

          MessageBox.Show( text );
        }

If you take a look at the code above, you can see that we have declared an object that represents a paragraph in a Word document. This is how you can extract text from a Word document, you get the paragraph object and you can access all the paragraphs that are contained in the list. The code loops thru every paragraph of a given document and displays them in a MessageBox.

Points of Interest

The new version of Office, Office 2003 is going to make things a little easier for Office developers. So if you are an Office developer, you should start looking into the features that Office 2003 has to offer. One of the nice features that I like is the capability of exporting documents into XML format.

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

Share

About the Author

Vahe Karamian
Software Developer Noorcon Inc.
United States United States
I have been programming since the age of 15. Started with BASIC on Apple II computers then moved on to Pascal. I wrote the game of Tetris using both languages on Apple II. At the age of 16 I got my first computer, and I started transferring the code over to Quick Basic. I then moved into C/C++ and have been developing in C/C++, until the introduction of the .Net Framework, when I switched over to C# and have been doing most of my development in C#.
 
Recently I left the corporate world, to start my own software consulting firm located in Los Angeles, California, specializing in the .Net Framework and technologies.
 
Vahé Karamian
www.noorcon.com
888.889.NOOR(6667)

Comments and Discussions

 
GeneralCell colors in tables... Pinmember93Current22-May-09 2:39 
Generalword instance is not visible Pinmemberlaljiparmar10-Jun-08 20:39 
GeneralSpecial characters [modified] PinmemberEuGenius_Krivbass27-May-08 1:24 
QuestionAutomating MS Word Using Visual Studio .NET PinmemberBonnieM25-Mar-08 6:55 
GeneralRe: Automating MS Word Using Visual Studio .NET PinmemberVahe Karamian25-Mar-08 7:34 
GeneralMemory release problem! Pinmemberlxb_champagne15-May-07 22:53 
Generalbytes to word file Pinmembersanbnayak19-Apr-07 22:34 
QuestionAdding page to MS Word.. Pinmemberaquarious202015-Apr-07 19:16 
AnswerRe: Adding page to MS Word.. Pinmembersalihovic2-Jun-08 22:04 
hi
try to merge to document:
i explane if you want to add a new page put it in a new document than use the merge method.
you find the merge method in this article
merge method [^]
 
nice to meet you

GeneralRe: Adding page to MS Word.. Pinmemberfriman4416-Oct-09 10:53 
AnswerRe: Adding page to MS Word.. PinmemberJohnny Glenn11-Apr-12 22:00 
QuestionRead & write microsoft word/Excel file & search a particular field Pinmembermadhu_su9-Apr-07 23:09 
GeneralDisplay ms word as a part of aspx page Pinmemberavias27-Mar-07 19:09 
GeneralAlternative automation method for easier change management & Word version compatibility Pinmemberdaluu30-Nov-06 14:23 
GeneralC++ example Pinmemberfons gufler20-Nov-06 22:46 
GeneralPrint to a word doc Pinmemberjerry_pendergraft27-Oct-06 4:45 
GeneralASP.NET PinmemberZeeshan_Fast15-Oct-06 23:45 
GeneralNo overload for method 'Open' takes '12' arguments PinmemberABlokha7710-Oct-06 7:21 
GeneralRe: No overload for method 'Open' takes '12' arguments PinmemberABlokha7710-Oct-06 7:25 
GeneralRe: No overload for method 'Open' takes '12' arguments PinmemberBodzioM30-Jan-08 11:51 
AnswerRe: No overload for method 'Open' takes '12' arguments PinmemberVahe Karamian10-Oct-06 8:08 
QuestionFind & Mark Paragraph containing text. Pinmemberverma-rahul7-Sep-06 17:21 
Generalnumber of words and frequency of a word in .doc file Pinmembersharma sanjeev16-Aug-06 20:05 
QuestionCompatibility across pc's Pinmembertmoney1019-Aug-06 18:46 
AnswerRe: Compatibility across pc's Pinmemberdaluu30-Nov-06 14:12 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 19 Dec 2003
Article Copyright 2003 by Vahe Karamian
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid