.Net Basic

This blogs gives introduction to C#.NET programming for beginners. This blogs assumes that you have no programming experience whatsoever. It's a lot easier than you think, and can be a very rewarding hobby!after Refer this blog

18 June 2009

Find and replace in Word Document

Note: add a reference to Microsoft.Office.Interop.Word (version 12) and the Using statement below

using Word = Microsoft.Office.Interop.Word;
public void FindAndReplaceTextInword(string Path, string FindText, string ReplaceText)
{

Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
// Define an object to pass to the API for missing parameters
object missing = System.Type.Missing;
try
{
// Everything that goes to the interop must be an object
object fileName = Path;

// Open the Word document.
// Pass the "missing" object defined above to all optional
// parameters. All parameters must be of type object,
// and passed by reference.
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);

// Activate the document
doc.Activate();

// Loop through the StoryRanges (sections of the Word doc)
foreach (Word.Range tmpRange in doc.StoryRanges)
{
// Set the text to find and replace
tmpRange.Find.Text = FindText;
tmpRange.Find.Replacement.Text = ReplaceText;


// Set the Find.Wrap property to continue (so it doesn't
// prompt the user or stop when it hits the end of
// the section)
tmpRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;

// Declare an object to pass as a parameter that sets
// the Replace parameter to the "wdReplaceAll" enum
object replaceAll = Word.WdReplace.wdReplaceAll;

// Execute the Find and Replace -- notice that the
// 11th parameter is the "replaceAll" enum object
tmpRange.Find.Execute(ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref replaceAll,
ref missing, ref missing, ref missing, ref missing);
}

// Save the changes
doc.Save();

// Close the doc and exit the app
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
catch (Exception ex)
{
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
}

Labels: ,