2

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">
Groger
  • 532
  • 3
  • 15
  • 1
    By `field "{NAME}"`, do you mean (a) just the text `{NAME}` written in your Word document or (b) an actual "Word field" (those things displayed with a gray background)? I don't think that Find-and-Replace works on the latter, you need to [do something like this](https://stackoverflow.com/a/17738336/87698) instead. – Heinzi Oct 27 '21 at 14:44
  • 1
    I have the text `"{NAME}"` in the word document. – Groger Oct 27 '21 at 15:10
  • 1
    can you please share sample of your document... – MD. RAKIB HASAN Oct 28 '21 at 06:19
  • It looks like you are trying to do word/mail-merge. and that is what it looks like as a binding back to the source document. Is the merge what you are actually trying to get done? If so, that is relatively easy to do. Please confirm. – DRapp Oct 28 '21 at 12:28
  • @DRapp I am not sure what a word/mail-merge is. I am just trying to replace text in a word document. – Groger Oct 28 '21 at 13:42
  • Word Merge is a way of having a template document with {placeholders} where you want to replace during the processing. A secondary document has nothing but a list of records such as a CSV of those {placeholder} values. Then with Word Merging, the data from the list is merged with the template document to create a final output document with exactly what you are looking to do find/replace. Use for bulk work. Can do with single record, or batch of 1000's as needed. Is this coming from a Word document? – DRapp Oct 28 '21 at 14:02
  • @DRapp Okay I think I understand. I am using C# to fill in the fields, though, not a second document or spreadsheet. – Groger Oct 28 '21 at 16:09

2 Answers2

1

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

Subbu
  • 2,130
  • 1
  • 19
  • 28
0

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

Glenn Keates
  • 121
  • 8
  • But can this be automated through C#? I specifically have an application that I need to be able to do this. – Groger Oct 28 '21 at 23:57
  • 1
    https://stackoverflow.com/questions/31874300/how-do-you-mail-merge-a-word-document-in-c-sharp – Glenn Keates Oct 29 '21 at 18:07
  • If no other answers are submitted, I will give this the bounty. Technically this doesn't answer my question since I asked specifically about the NetOffice framework, but this provides a good alternative. – Groger Oct 31 '21 at 19:55