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

Word 2007 Automation

By , 8 May 2007
 

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)

About the Author

joaquimc
Web Developer
Portugal Portugal
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionInterop word dll property if document has changedmemberjemino23 Mar '09 - 22:50 
GeneralWindows 64 bits.memberpcct19765 Sep '08 - 7:19 
GeneralFormFieldsmemberLechuss28 Nov '07 - 10:29 
QuestionDo you know how to choose the printer?membervincent901529003310 Jul '07 - 15:35 
AnswerRe: Do you know how to choose the printer?memberLee Bottone15 Jul '07 - 22:54 
GeneralRe: Do you know how to choose the printer?membervincent901529003315 Jul '07 - 23:18 
GeneralRe: Do you know how to choose the printer?memberguden17 Oct '07 - 3:10 
GeneralWord automation on windows 2003 servermemberwildox14 Jun '07 - 0:45 
GeneralRe: Word automation on windows 2003 servermemberEvilWeeble16 Oct '07 - 23:59 
Generaldocx formatmemberFergal Boden8 May '07 - 5:00 
GeneralRe: docx formatmemberjoaquimc8 May '07 - 6:49 
GeneralRe: docx formatmemberFergal Boden8 May '07 - 6:57 
GeneralRe: docx formatmemberLee Bottone15 Jul '07 - 23:06 
GeneralRe: docx formatmemberJohnny Glenn13 Mar '12 - 23:41 
QuestionExample?memberirrdev8 May '07 - 4:57 
AnswerRe: Example?memberjoaquimc8 May '07 - 7:42 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 8 May 2007
Article Copyright 2007 by joaquimc
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid