我有一个模板文件,其中放置了两个占位符。两者都是纯文本内容控件。我有以下代码,我在其中将值设置为文件中的占位符。
static void Main(string[] args)
{
string fileName = "C:\\xxx\\Template.docx";
byte[] fileContent = File.ReadAllBytes(fileName);
using (MemoryStream memStream = new MemoryStream())
{
memStream.Write(fileContent, 0, (int)fileContent.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStream,true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
var sdtElements = wordDoc.MainDocumentPart.Document.Descendants<SdtElement>();
foreach (SdtElement sdtElement in sdtElements)
{
Tag blockTag = sdtElement.SdtProperties.Descendants<Tag>().ElementAt(0);
Run nr = new Run();
Text txt = new Text();
txt.Text = "RKS";
nr.Append(txt);
Lock lckContent = new Lock();
bool lockControl = true;
if (lockControl)
{
lckContent.Val = LockingValues.SdtContentLocked;
}
else
{
lckContent.Val = LockingValues.Unlocked;
}
if (sdtElement is SdtBlock)
{
(((SdtBlock)sdtElement).SdtContentBlock.ElementAt(0)).RemoveAllChildren();
(((SdtBlock)sdtElement).SdtContentBlock.ElementAt(0)).AppendChild<Run>(nr);
((SdtBlock)sdtElement).SdtProperties.Append(lckContent);
}
if (sdtElement is SdtCell)
{
((SdtCell)sdtElement).SdtContentCell.ElementAt(0).Descendants<Paragraph>().ElementAt(0).RemoveAllChildren(); ((SdtCell)sdtElement).SdtContentCell.ElementAt(0).Descendants<Paragraph>().ElementAt(0).AppendChild<Run>(nr);
((SdtCell)sdtElement).SdtProperties.Append(lckContent);
}
if (sdtElement is SdtRun)
{
//SdtContentText text = sdtElement.SdtProperties.Elements<SdtContentText>().FirstOrDefault();
//((SdtRun)sdtElement).SdtContentRun.ElementAt(0).AppendChild<Text>(emptyTxt);
((SdtRun)sdtElement).SdtContentRun.ElementAt(0).RemoveAllChildren();
((SdtRun)sdtElement).SdtContentRun.ElementAt(0).AppendChild<Run>(nr);
((SdtRun)sdtElement).SdtProperties.Append(lckContent);
}
}
wordDoc.MainDocumentPart.Document.Save();
}
}
}
代码成功运行,但更改未反映在文件中。
我错过了什么?