I need to replace text into MergeField
and do it simply text. I found question on the topic. It works for me. This code changes the text, but leaves the field as MergeField
. And other question that change MergeField
to text. But if there are several such fields in one line, the second one will be deleted.
At this point, I've tweaked the code from the first link a bit. What do I need to add to change MergeField
to text?
string sourceFile = @"C:\Users\Owl\Desktop\Template.docm";
string targetFile = @"C:\Users\Owl\Desktop\Result.docx";
File.Copy(sourceFile, targetFile, true);
using (WordprocessingDocument document = WordprocessingDocument.Open(targetFile, true))
{
document.ChangeDocumentType(WordprocessingDocumentType.Document);
foreach (FieldCode field in document.MainDocumentPart
.RootElement.Descendants<FieldCode>())
{
int indexEndName = field.Text.IndexOf("\\");
string fieldName = string.Format("«{0}»",
field.Text.Substring(11, indexEndName - 11).Trim());
foreach (Run run in document.MainDocumentPart.Document.Descendants<Run>())
{
foreach (Text txtFromRun in run.Descendants<Text>()
.Where(a => a.Text == fieldName))
{
txtFromRun.Text = "some text";
}
}
}
document.MainDocumentPart.Document.Save();
}
UPDATE
I made a mistake. The code on the second link. The second field in the line not deleted. It stays. But does not fall into the cycle, is ignored. I don't understand why.