我需要将文本替换为MergeField
简单的文本。我发现了有关该主题的问题。这个对我有用。此代码更改文本,但将字段保留为MergeField
. 以及其他变成MergeField
文本的问题。但如果一行中有多个这样的字段,则第二个将被删除。
在这一点上,我已经稍微调整了第一个链接中的代码。我需要添加什么来更改MergeField
文本?
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();
}
更新
我犯了一个错误。第二个链接上的代码。行中的第二个字段未删除。它留下来。但不落入循环,被忽略。我不明白为什么。