I'm trying to replace some placeholder words in a DOCX document using Word Interop. Every placeholder gets replaced correctly except for one. I want the single word "ContentX" in my document to be replaced by an enumerated list of lines (the enumeration should be retained).
In my DOCX template, the placeholder looks like this (with a bullet):
• ContentX
After running my code, I get the following result:
• Hello
• World
• Its
• a
• Test
Notice that almost every line has an unwanted leading space. I already verified that the replacement string itself is exactly as expected: "Hello\r\nWorld\r\nIts\r\na\r\nTest\r\n"
Here is the relevant part of my code:
Dictionary<string, string> replacements = new Dictionary<string, string>
{
{"999", berichtsHeftNR},
{"name1", settingsName},
{"jahr1", settingsJahr},
{"abteilung1", settingsAbteilung},
{"DatumVon", dateTimeValue.ToString("dd.MM.yyyy")},
{"DatumBis", dateTimeValue.AddDays(4).ToString("dd.MM.yyyy")},
{"38,5", settingsGesamtStunden },
{"ContentX", contentBuilder.ToString().Trim()},
};
foreach (Section section in doc.Sections)
{
Range sectionRange = section.Range;
foreach (var replacement in replacements)
{
Debug.WriteLine("[WordProzess]:" + replacement.Value.ToString());
sectionRange.Find.ClearFormatting();
sectionRange.Find.Text = replacement.Key;
sectionRange.Find.Replacement.ClearFormatting();
sectionRange.Find.Replacement.Text = replacement.Value;
sectionRange.Find.Execute(Replace: WdReplace.wdReplaceAll);
}
}
Does anyone know why extra spaces appear in the resulting document, or how I can prevent them?
I've confirmed that the string built in contentBuilder doesn't contain any unwanted spaces.