Replace Text in Word Document

4k views Asked by At

I am using the NetOffice library to edit a Word document. In my document, I have a field "{NAME}" that I would like to replace with a value "John Smith". However, executing the following code does not work. Find.Execute returns false, indicating failure, and no change is reflected in document.Content.Text.

// Open the template
Application word = new Application();
Document document = word.Documents.Open(fileName, false, true);

// Set up initial behavior in word
word.Visible = false;

// Replace template with final values
foreach (LetterField field in fields)
{
    document.Content.Find.ClearFormatting();
    document.Content.Find.Text = "{" + field.Key + "}";
    document.Content.Find.Replacement.ClearFormatting();
    document.Content.Find.Replacement.Text = field.Value;
    document.Content.Find.Execute(null, null, null, null, null, null, null, null, null, null, WdReplace.wdReplaceAll);
}

I also tried manually replacing document.Content.Text, but this removes all formatting from the page, which is also undesirable. How can I replace text in a document in NetOffice?

I notice that setting document.Content.Find.Text does not seem to do anything, as checking the value still yields "", even after setting it to something else. Is this intended behavior, or am I missing something?

The document contains the following (copied and pasted):

Date: {DATE}
{NAME}
{ADDRESSLINE}
{ADDRESSCITY}, {ADDRESSSTATE} {ADDRESSCODE}

Some fields are as follows:

<"NAME", "John Smith">
<"DATE", "10/28/2021">
2

There are 2 answers

0
Subbu On BEST ANSWER

I started with your sample, but, tried with a variation of the Execute method and it works fine for me.

        const string TemplateFileName = @"D:\Dev\SO\MyWordDoc.docx";
        const string ResultFileName = @"D:\Dev\SO\MyWordDoc_new.docx";

        var wordApp = new Application();
        var doc = wordApp.Documents.Open(TemplateFileName, false, true);
        var status = doc.Content.Find.Execute(findText: "{NAME}", 
                                    matchCase: false,
                                    matchWholeWord: false,
                                    matchWildcards: false,
                                    matchSoundsLike: false,
                                    matchAllWordForms: false,
                                    forward: true, //this may be the one
                                    wrap: false,
                                    format: false,
                                    replaceWith: "My Name Value", 
                                    replace: WdReplace.wdReplaceAll
                                    );

        doc.SaveAs(ResultFileName);
        doc.Close();

I used the syntax from: https://learn.microsoft.com/en-us/office/vba/api/Word.Find.Execute

for the different parameters.

It may be that you may need to Execute with forward parameters to be "True", i.e., the 7th parameter.

Result document: enter image description here

3
Glenn Keates On

What you're trying to do here looks like it could be achieved by using the Mail Merge feature built into word. The feature is designed to take in a list of contact information and replace placeholder text to produce a document addressed to each person in the list.

Microsoft has some good documentation on how to achieve this which I suggest you check out https://support.microsoft.com/en-us/office/use-mail-merge-for-bulk-email-letters-labels-and-envelopes-f488ed5b-b849-4c11-9cff-932c49474705