Search code examples
.netreplacems-wordms-office

Fastest way to programmatically replace text in a Word document


The task is to replace specific keywords in a Word document using .NET. What would be the fastest and most reliable way to make it retaining original formatting and document structure?


Solution

  • If you have word installed then it's pretty trivial.

    Referencing the Word doc assembly from the GAC. You can load up a word document and replace data in it.

    This is from an app I have here to print word documents by putting in client names and such. (cut and pasted sections)

        public void ReplaceWordDoc(ref Document doc, object data)
        {
            object missing = Missing.Value;
    
            List<ReplacerSearch> search = GetSearchList(data);
    
            foreach (var searchItem in search)
            {
                foreach (Range tmpRange in ((Document)doc).StoryRanges)
                {
                    // Set the text to find and replace
                    tmpRange.Find.Text = searchItem.Find;
                    tmpRange.Find.Replacement.Text = searchItem.Replace;
    
                    // 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 = WdFindWrap.wdFindContinue;
    
                    // Declare an object to pass as a parameter that sets
                    // the Replace parameter to the "wdReplaceAll" enum
                    object replaceAll = 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);
                }
            }
        }
    

    ^This part does the find/replace. The list of ReplacerSearch (wow bad name) is just two properties, Find, Replace. Find is the text to find, Replace is the text to replace with.

    Then the code below, based on a given filename (path/name) it creates an instance of word (i think) and opens the document, does the replacement, and then you can save or print or what ever.

        object  fileName        = string.Empty,
                trueValue       = true,
                missing         = Missing.Value,
                falseValue      = false;
        var     app             = new ApplicationClass();
        var doc = new Document();
    
    try
    {
        doc = app.Documents.AddOld(ref fileName, ref missing);
        //doc = app.Documents.Add(ref fileName, ref missing, ref missing, ref missing);
    
        // Loops through the StoryRanges (sections of the Word doc)
        ReplaceWordDoc(ref doc, item);
    
        //Save or print...
    }
    catch (Exception ex)
    {
        Helpers.Logger.WriteToEventLog(ex.Message, EventLogEntryType.Error);
    }
    finally
    {
        if (doc != null)
        {
            doc.Close(ref falseValue, ref missing, ref missing);
        }
    }
    
    if (app != null)
    {
        app.Application.Quit(ref falseValue, ref missing, ref missing);
    }
    

    Hope that helps.