Click here to Skip to main content
11,412,834 members (74,773 online)
Click here to Skip to main content

Tagged as

Edit Microsoft Word Document From Your Application

, 14 May 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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.
    using Word = Microsoft.Office.Interop.Word;//<- this is what I am talking about
  2. Code behind the button:
    //	
    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():
    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)

Share

About the Author

Rudra Sankar
Software Developer
India India
I love coding.... yes.... I do....!

Comments and Discussions

 
QuestionHow to handle check box and radio button in same example? Pin
shiva2239 at 3-Apr-15 1:47
membershiva22393-Apr-15 1:47 
QuestionHow do I replace the text which is in some font in Word Document? Pin
Nirajan Pant at 29-Dec-14 16:21
memberNirajan Pant29-Dec-14 16:21 
GeneralMy vote of 1 Pin
Tony4966 at 13-Oct-14 3:25
memberTony496613-Oct-14 3:25 
Questionmissing Pin
aalhanane at 18-Dec-13 13:32
memberaalhanane18-Dec-13 13:32 
SuggestionCode doesn't work as expected Pin
Pavan Gayakwad at 20-Mar-13 1:36
memberPavan Gayakwad20-Mar-13 1:36 
SuggestionFor those experiencing issues... Pin
Alejandro Miralles at 23-Nov-12 6:43
memberAlejandro Miralles23-Nov-12 6:43 
Here is an alternative approach in case you wanna try something else http://alemiralles.blogspot.com.ar/2012/11/how-to-create-word-documents-from.html[^]
QuestionRecive Error Pin
helpsos at 10-Aug-12 18:18
memberhelpsos10-Aug-12 18:18 
GeneralMy vote of 5 Pin
Madhusudhan143 at 23-Jun-12 2:15
memberMadhusudhan14323-Jun-12 2:15 
Generaltank you Pin
morteza fakoor at 23-May-12 0:51
membermorteza fakoor23-May-12 0:51 
QuestionError on execution Pin
mimo1450 at 4-Mar-12 2:31
membermimo14504-Mar-12 2:31 
QuestionHow about using mail merge? Pin
Robert Hutch at 1-Mar-12 1:02
memberRobert Hutch1-Mar-12 1:02 
GeneralMy vote of 5 Pin
poornesh sharma at 28-Feb-12 2:10
memberpoornesh sharma28-Feb-12 2:10 
BugError in process Pin
Sarvesh Kumar Gupta at 19-Nov-11 0:47
memberSarvesh Kumar Gupta19-Nov-11 0:47 
QuestionThank you! Pin
c4mel0t at 14-Jul-11 0:06
memberc4mel0t14-Jul-11 0:06 
GeneralEdit Microsoft Word Document From Your Application Pin
amitrajahuja at 23-Nov-10 4:36
memberamitrajahuja23-Nov-10 4:36 
Generalquestion Pin
waelstaitieh at 5-Mar-10 23:57
memberwaelstaitieh5-Mar-10 23:57 
GeneralOffice Versions Pin
maspr at 20-May-09 4:13
membermaspr20-May-09 4:13 
GeneralRe: Office Versions Pin
Jacques Bourgeois at 20-May-09 14:52
memberJacques Bourgeois20-May-09 14:52 
GeneralRe: Office Versions Pin
Bhuvnesh Pandey at 14-May-13 20:53
memberBhuvnesh Pandey14-May-13 20:53 
GeneralImages Pin
stevennuon at 19-May-09 23:24
memberstevennuon19-May-09 23:24 
GeneralOuch! Pin
Jacques Bourgeois at 19-May-09 14:44
memberJacques Bourgeois19-May-09 14:44 
GeneralRe: Ouch! Pin
morajo at 19-May-09 21:03
membermorajo19-May-09 21:03 
GeneralRe: Ouch! Pin
Jacques Bourgeois at 20-May-09 14:39
memberJacques Bourgeois20-May-09 14:39 
QuestionHow to open word doc from stream Pin
ivansmilj at 19-May-09 5:17
memberivansmilj19-May-09 5:17 
GeneralAKA Com Pin
Norm .net at 14-May-09 1:42
memberNorm .net14-May-09 1: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
Web01 | 2.8.150427.1 | Last Updated 14 May 2009
Article Copyright 2009 by Rudra Sankar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid