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">
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.