Automating MS Word Using Visual Studio .NET(收藏)

类别:.NET开发 点击:0 评论:0 推荐:


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


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

        // 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

        // Paste into new document as unformatted text
        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.


        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.