Click here to Skip to main content
Click here to Skip to main content

Word 2007 Automation

, 8 May 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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:

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)

Share

About the Author

joaquimc
Web Developer
Portugal Portugal
No Biography provided

Comments and Discussions

 
QuestionInterop word dll property if document has changed Pinmemberjemino23-Mar-09 23:50 
GeneralWindows 64 bits. Pinmemberpcct19765-Sep-08 8:19 
GeneralFormFields PinmemberLechuss28-Nov-07 11:29 
QuestionDo you know how to choose the printer? Pinmembervincent901529003310-Jul-07 16:35 
AnswerRe: Do you know how to choose the printer? PinmemberLee Bottone15-Jul-07 23:54 
GeneralRe: Do you know how to choose the printer? Pinmembervincent901529003316-Jul-07 0:18 
GeneralRe: Do you know how to choose the printer? Pinmemberguden17-Oct-07 4:10 
GeneralWord automation on windows 2003 server Pinmemberwildox14-Jun-07 1:45 
GeneralRe: Word automation on windows 2003 server PinmemberEvilWeeble17-Oct-07 0:59 
Generaldocx format PinmemberFergal Boden8-May-07 6:00 
GeneralRe: docx format Pinmemberjoaquimc8-May-07 7:49 
GeneralRe: docx format PinmemberFergal Boden8-May-07 7:57 
GeneralRe: docx format PinmemberLee Bottone16-Jul-07 0:06 
GeneralRe: docx format PinmemberJohnny Glenn14-Mar-12 0:41 
QuestionExample? Pinmemberirrdev8-May-07 5:57 
AnswerRe: Example? Pinmemberjoaquimc8-May-07 8:42 

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 | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 8 May 2007
Article Copyright 2007 by joaquimc
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid