Click here to Skip to main content
15,921,990 members
Articles / Programming Languages / C#
Article

Word 2007 Automation

Rate me:
Please Sign up or sign in to vote.
3.65/5 (10 votes)
8 May 2007CPOL2 min read 108.1K   3.5K   36   16
Using C# to open and do some automation tasks in a Microsoft Word 2007 document

Introduction

I am new to the C# world and my boss can't wait for the job to get done. So I was forced to start the work before I knew how to do it.

I have a project where I need to pass some values from a datatable to an existing Word 2007 document, and print it. I spent the last few days looking for some samples where I could see how to do that, but none of those samples did what I needed.

I was forced to try some of the C# namespaces and see if they do that.

If you are trying to do something like this, I think that the code I present here will help you.

Using the Code

There are some ways to edit a Word 2007 document: In Microsoft articles (at least the ones I've read about the subject), you are forced to understand the "*.docx" format. If you understand that the underlying format is XML in a zipped package, you are half way to understanding the way to edit it, but I needed something simpler: my task was simple and what I needed was simple automation.

Below is all the code you need to open a Word 2007 document, change some sentences (with further exploitation, you can add tables, change formats, ...), print the document, and even open your mail client to send this document to someone as an attachment.

C#
private void met_word_automation()
{   
    try
      {
           // Declaring the object variables we will need later
            object varFileName = "c:\temp\doc.docx";
            object varFalseValue = false;
            object varTrueValue = true;
            object varMissing = Type.Missing;
            string varText;

            // Create a reference to Microsoft Word application
            Microsoft.Office.Interop.Word.Application varWord = 
                new Microsoft.Office.Interop.Word.Application(); 
            // Creates a reference to a Word document
            Microsoft.Office.Interop.Word.Document varDoc =
                varWord.Documents.Open(ref varFileName, ref varMissing,
                   ref varFalseValue, 
                   ref varMissing, ref varMissing, ref varMissing, ref varMissing, 
                   ref varMissing, ref varMissing, ref varMissing, 
                   ref varMissing, ref varMissing, ref varMissing, ref varMissing, 
                   ref varMissing, ref varMissing);
            // Activate the document
            varDoc.Activate();
            // Change the 1<sup>st</sup> sentence of the document 
            varText = "Altered sentence nr. 1";
            varDoc.Sentences[0].Text = varText;
            // Change the 3<sup>rd</sup> sentence of the document 
            varText = "Altered sentence nr. 3";
            varDoc.Sentences[2].Text = varText;
            // Save the document
            varDoc.Save();
            // Show the Microsoft Word window with our document on it
            varWord.Visible = true;
            // Call the print dialog in Word
            Microsoft.Office.Interop.Word.Dialog varDlg = 
                varWord.Application.Dialogs[
                Microsoft.Office.Interop.Word.WdWordDialog.wdDialogFilePrint];
            varDlg.Show(ref varMissing);
            // Print the document
            varDoc.PrintOut(ref varTrueValue, ref varFalseValue, ref varMissing,
                    ref varMissing, ref varMissing, ref varMissing, 
                    ref varMissing, ref varMissing, ref varMissing, ref varMissing,
                    ref varFalseValue, ref varMissing, ref varMissing, 
                    ref varMissing, ref varMissing, ref varMissing, ref varMissing,
                    ref varMissing);
            // Send mail with this document as an attachment
            varDoc.SendMail();
    }
    catch (Exception varE)
    {
            MessageBox.Show("Error:\n" + varE.Message, "Error message");
    }
}

You need to create references to this .NET namespace in order to use the above code:

C#
Microsoft.Office.Interop.Word

This namespace is in the Msword.olb COM library which is usually in the folder C:\Program Files\Microsoft Office\Office12.

Add the reference this way: Menu 'Project', 'Add reference', then select 'COM' separator and search for that library.

I hope this code will be of some use to you.

P. S. By IRRDEV request, you can download a Visual Studio 2005 project with a form. This form has a button that opens a Word doc and replaces every paragraph with other text. The path for the document is hard-coded inside the button click event, you must change the path to the Word file.

History

  • 8th May, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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

Comments and Discussions

 
QuestionInterop word dll property if document has changed Pin
jemino23-Mar-09 22:50
jemino23-Mar-09 22:50 
GeneralWindows 64 bits. Pin
pcct19765-Sep-08 7:19
pcct19765-Sep-08 7:19 
GeneralFormFields Pin
Lechuss28-Nov-07 10:29
Lechuss28-Nov-07 10:29 
QuestionDo you know how to choose the printer? Pin
vincent901529003310-Jul-07 15:35
vincent901529003310-Jul-07 15:35 
AnswerRe: Do you know how to choose the printer? Pin
Lee Bottone15-Jul-07 22:54
Lee Bottone15-Jul-07 22:54 
GeneralRe: Do you know how to choose the printer? Pin
vincent901529003315-Jul-07 23:18
vincent901529003315-Jul-07 23:18 
GeneralRe: Do you know how to choose the printer? Pin
guden17-Oct-07 3:10
guden17-Oct-07 3:10 
GeneralWord automation on windows 2003 server Pin
wildox14-Jun-07 0:45
wildox14-Jun-07 0:45 
GeneralRe: Word automation on windows 2003 server Pin
EvilWeeble16-Oct-07 23:59
EvilWeeble16-Oct-07 23:59 
Generaldocx format Pin
Fergal Boden8-May-07 5:00
Fergal Boden8-May-07 5:00 
GeneralRe: docx format Pin
joaquimc8-May-07 6:49
joaquimc8-May-07 6:49 
GeneralRe: docx format Pin
Fergal Boden8-May-07 6:57
Fergal Boden8-May-07 6:57 
GeneralRe: docx format Pin
Lee Bottone15-Jul-07 23:06
Lee Bottone15-Jul-07 23:06 
While I agree with you that it can make matters difficult, I have also seen Word automation simplify an operation, making it easier for the person who has to do the task after the coder is gone. Within the last 2 years, I have created three Microsoft Word automation applications that as part of there processing, open an Excel document, import data, create users and rights in different places, and print appropriate letters to send to the users (From a Microsoft Word document). As this can be anywhere from 100 to 6000 letters each run, the automation saves the person who runs the application time, and therefore saves our company money.

The trick (as with any coding) is ERROR CHECKING. If you do not understand how to error check in automation (and tell the user how to fix any issues that occur), you should not run it. The example code I have seen on here to automate Microsoft Word seems to leave the bulk of the error checking out, in order to make the code simpler so we can understand what is happening.

I think I will start work on a code segment that I can post here that shows how to error check a Microsoft Word automation project in order to ensure that you catch a majority of the errors (and understand what causes the errors).

Lee Bottone
GeneralRe: docx format Pin
Johnny Glenn13-Mar-12 23:41
Johnny Glenn13-Mar-12 23:41 
QuestionExample? Pin
irrdev8-May-07 4:57
irrdev8-May-07 4:57 
AnswerRe: Example? Pin
joaquimc8-May-07 7:42
joaquimc8-May-07 7:42 

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.