Click here to Skip to main content
15,891,692 members
Articles / Productivity Apps and Services / Microsoft Office

Edit Microsoft Word Document From Your Application

Rate me:
Please Sign up or sign in to vote.
4.24/5 (16 votes)
14 May 2009CPOL1 min read 154.1K   40   27
Create & edit Microsoft Word document from Windows application Form by using C#

Introduction

I faced this problem when I was developing a small tool to write official letters. My requirements were, letter template & content can be changed any time and application will help to get only inputs like, sent to name, organization name, date, etc. and after that when user presses finish button, the letter should be ready for print out along with predefined content & inputs. 

Background

To solve this, I used Microsoft VS 2005 with C# 2.0. 

Here are the steps I followed:  

Add Microsoft.Office.Interop.Word reference to the project from COM Component as follows:

addref.GIF

This will automatically add VBIDE, Microsoft.Office.Core along with Microsoft.Office.Interop.Word as references.

Now create a Microsoft Word document with the fields <Name>, <Date>, <Subject> and letter body. Then place all 3 variables (I called these variables because these will be changed automatically based on user input) where they belong. I did the following:

editword.GIF

Now design your form in VS IDE. I did it like this:

formdesign.GIF

Using the Code

  1. Now let's do some coding…..ya….. so here is my sample coding.
    C#
    using Word = Microsoft.Office.Interop.Word;//<- this is what I am talking about
  2. Code behind the button:
    C#
    //	
    private void btnlettergen_Click(object sender, EventArgs e)
    {
    //  create offer letter
                    try
                    {
    //  Just to kill WINWORD.EXE if it is running
                        killprocess("winword");	
    //  copy letter format to temp.doc
                        File.Copy("C:\\OfferLetter.doc", "c:\\temp.doc", true);   
    //  create missing object
                        object missing = Missing.Value;
    //  create Word application object
                        Word.Application wordApp = new Word.ApplicationClass();
    //  create Word document object
                        Word.Document aDoc = null;
    //  create & define filename object with temp.doc
                        object filename = "c:\\temp.doc";
    //  if temp.doc available
                        if (File.Exists((string)filename))  
                        {
                            object readOnly = false;
                            object isVisible = false;
    //  make visible Word application
                            wordApp.Visible = false;
    //  open Word document named temp.doc
                            aDoc = wordApp.Documents.Open(ref filename, ref missing, 
    			ref readOnly, ref missing,ref missing, ref missing, 
    			ref missing, ref missing, ref missing, ref missing, 
    			ref missing,ref isVisible, ref missing, ref missing, 
    			ref missing, ref missing);
                            aDoc.Activate();
    //  Call FindAndReplace()function for each change
                            this.FindAndReplace(wordApp, "<Date>", dtpDate.Text);
                            this.FindAndReplace(wordApp, "<Name>", txName.Text.Trim());
                            this.FindAndReplace(wordApp, "<Subject>", 
    					txtSubject.Text.Trim());
    //  save temp.doc after modified
                            aDoc.Save();
                        }
                        else
                            MessageBox.Show("File does not exist.", 
    				"No File", MessageBoxButtons.OK, 
    				MessageBoxIcon.Information);
                        killprocess("winword");
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error in process.", "Internal Error", 
    			MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
    }
  3. Create FindAndReplace():
    C#
    private void FindAndReplace(Word.Application wordApp, 
    			object findText, object replaceText)
    {   
                object matchCase = true;
                object matchWholeWord = true;
                object matchWildCards = false;
                object matchSoundsLike = false;
                object matchAllWordForms = false;
                object forward = true;
                object format = false;
                object matchKashida = false;
                object matchDiacritics = false;
                object matchAlefHamza = false;
                object matchControl = false;
                object read_only = false;
                object visible = true;
                object replace = 2;
                object wrap = 1;
                wordApp.Selection.Find.Execute(ref findText, ref matchCase,
                    ref matchWholeWord, ref matchWildCards, ref matchSoundsLike,
                    ref matchAllWordForms, ref forward, ref wrap, ref format,
                    ref replaceText, ref replace, ref matchKashida, 
    						ref matchDiacritics,
                    ref matchAlefHamza, ref matchControl);
    }

Now check out your temp.doc file in C:\, all variables defined under ‘<>’ are replaced with the input values. How's that! 

So, enjoy your coding….. happy coding!

History

  • 14th May, 2009: Initial post

License

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


Written By
Software Developer
India India
I love coding.... yes.... I do....!

Comments and Discussions

 
Questionmissing download link Pin
developerc sapphire5-Jan-18 20:19
developerc sapphire5-Jan-18 20:19 
QuestionClearFormatting(), Marshal.ReleaseComObject(object) left out! Pin
kp4231-Aug-16 9:27
kp4231-Aug-16 9:27 
QuestionHow to handle check box and radio button in same example? Pin
shiva22393-Apr-15 0:47
shiva22393-Apr-15 0:47 
QuestionHow do I replace the text which is in some font in Word Document? Pin
Nirajan Pant29-Dec-14 15:21
Nirajan Pant29-Dec-14 15:21 
GeneralMy vote of 1 Pin
Tony496613-Oct-14 2:25
Tony496613-Oct-14 2:25 
Questionmissing Pin
aalhanane18-Dec-13 12:32
aalhanane18-Dec-13 12:32 
SuggestionCode doesn't work as expected Pin
Pavan Gayakwad20-Mar-13 0:36
Pavan Gayakwad20-Mar-13 0:36 
SuggestionFor those experiencing issues... Pin
Alejandro Miralles23-Nov-12 5:43
Alejandro Miralles23-Nov-12 5:43 
QuestionRecive Error Pin
mymina10-Aug-12 17:18
mymina10-Aug-12 17:18 
GeneralMy vote of 5 Pin
Madhusudhan14323-Jun-12 1:15
Madhusudhan14323-Jun-12 1:15 
Generaltank you Pin
morteza fakoor22-May-12 23:51
morteza fakoor22-May-12 23:51 
QuestionError on execution Pin
Moneer Tarabishi4-Mar-12 1:31
Moneer Tarabishi4-Mar-12 1:31 
QuestionHow about using mail merge? Pin
Robert Hutch1-Mar-12 0:02
Robert Hutch1-Mar-12 0:02 
GeneralMy vote of 5 Pin
poornesh sharma28-Feb-12 1:10
professionalpoornesh sharma28-Feb-12 1:10 
BugError in process Pin
Sarvesh Kumar Gupta18-Nov-11 23:47
Sarvesh Kumar Gupta18-Nov-11 23:47 
QuestionThank you! Pin
c4mel0t13-Jul-11 23:06
c4mel0t13-Jul-11 23:06 
GeneralEdit Microsoft Word Document From Your Application Pin
amitrajahuja23-Nov-10 3:36
amitrajahuja23-Nov-10 3:36 
Generalquestion Pin
waelstaitieh5-Mar-10 22:57
waelstaitieh5-Mar-10 22:57 
GeneralOffice Versions Pin
maspr20-May-09 3:13
maspr20-May-09 3:13 
GeneralRe: Office Versions Pin
Jacques Bourgeois20-May-09 13:52
Jacques Bourgeois20-May-09 13:52 
GeneralRe: Office Versions Pin
Bhuvnesh Pandey14-May-13 19:53
Bhuvnesh Pandey14-May-13 19:53 
GeneralImages Pin
stevennuon19-May-09 22:24
stevennuon19-May-09 22:24 
GeneralOuch! PinPopular
Jacques Bourgeois19-May-09 13:44
Jacques Bourgeois19-May-09 13:44 
Good intentions, and I suppose that this is code that might works in that simple situation. But it shows a lack of understanding of how to manipulate Word and is a very bad example of techniques to use on a general basis. There are a few dangerous things in that code, and things that could be done a lot better.

-----

First of all, marking the document with <Tags> works, but there is a better way, by using bookmarks in the document. Bookmarks being objects, they are a lot more interesting for programmer to mark places where they should intervene in a document. Search Word documentation for bookmarks. They also make your code work a lot faster than FindAndReplace in big documents.

-----

<pre>killprocess("winword");</pre>

If the user has a copy of Word opened with one or more documents opened, you are forcing Word to close and the user will probably lose all the modifications made to the documents since the last save. <b>Never kill a process that is an application that could have been started by the user</b>.

You do not need to kill a previously running instance of Word to start another one. Creating a new one with new Word.ApplicationClass() will simply start a second invisible copy of Word. The user can continue to work in the copy that he/she started, and your application works in the new one you created.

-----

Instances of Word started from an application are not Visible by default, which is often a good thing, because they will run faster (they do not have to refresh the screen each time you do something in the document), and the user is in your application, he does not need to see the document.

However, since it is invisible, the user cannot close the copy of Word you are starting through code (unless you make the Application object (wordApp) visible through its Visible property).

It is thus very important for your code to close the Word instance once your work is done by calling the Quit method of the Application object (wordApp).

Failing to do so, if the user calls your code 25 times, there will 25 copies of Word running on the computer. At 10 MBs or more a piece, that is a lot of memory.

You do not see them as applications because they are invisible to the user, but if you go in the Windows Task List, you will see them running as processes. They will close down only if killed from the task list of if the user reboot the computer.

A .NET application that starts a COM object such as any of the Office applications should be very careful to close the application, specially if it is not visible to the user.

-----

<pre>File.Copy("C:\\OfferLetter.doc", "c:\\temp.doc", true);</pre>

Although this does what it is supposed to do , it is not the right way to work in Word. The template document should be saved as a template (an option in Word), and the new document should be created from that template. See Templates in Word help. Not only is more efficient in the long run but it also makes for simpler code when you want to create the document.

aDoc= wordApp.Documents.Add (ref filename, ref missing, ref missing, ref missing);

-----

Note that Missing.Value is part of the System.Reflection namespace and is not available unless you specify that namespace or add a using clause for it.

-----

<i>For all users</i>

The Office Primary Interop Assembly (PIA) should be installed on the development computer and the client computers if you want everything to work correctly. Otherwise, you will have problems with properties or methods that use Variant variables which are quite common in Office, but not available in .NET. The PIA, available from Microsoft or installed as an option both when you install Visual Studio and Office (in office, it is called the .NET components or something like that the installation option windows). They are also available only for Office 2003 and over.

<i>For VB users</i>

Do not use a Word.ApplicationClass, use a Word.Application object instead. The Word ApplicationClass is a wrapper that handles a few problems C# has with Word, such as optional parameters for some methods. VB does not need the wrapper sinde Optional parameters are available in VB.

You thus do not have to pass all those useless Missing parameters since VB does not requires them on optional parameters.

Jacques Bourgeois

GeneralRe: Ouch! Pin
morajo19-May-09 20:03
morajo19-May-09 20:03 
GeneralRe: Ouch! Pin
Jacques Bourgeois20-May-09 13:39
Jacques Bourgeois20-May-09 13:39 

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.