我正在学习OpenXML。已经花了很多时间搜索如何在C#中将文本插入内容控件。
我有一个模板文档,其中包含两个控件“Name”和“Age”。我可以找到它们,但是我无法在它们中添加文本。我尝试了很多方法,但都没有成功。
byte[] templateBytes = System.IO.File.ReadAllBytes(fileName);
using (MemoryStream templateStream = new MemoryStream())
{
templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
using (WordprocessingDocument outDoc = WordprocessingDocument.Open(templateStream, true))
{
MainDocumentPart mainPart = outDoc.MainDocumentPart;
foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>().ToList())
{
SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
if (alias != null)
{
string sdtTitle = alias.Val.Value;
switch (sdtTitle)
{
case "Name":
// ¿Qué?
break;
case "Age":
// ¿Qué?
break;
}
}
}
outDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
}
using (FileStream fileStream = new FileStream(savePath, System.IO.FileMode.CreateNew))
{
templateStream.WriteTo(fileStream);
}
}
非常感谢您的帮助。
谢谢,
Tim。
编辑--
感谢您的回复。根据您的建议,我尝试使用生产力工具进行转换和钻取以查找要更新的子元素。您能否告诉我为什么这段代码根本没有写入任何内容?
foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>().ToList())
{
SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
if (alias != null)
{
SdtRun xRun = (SdtRun)sdt;
SdtContentRun xContentRun = xRun.Descendants<SdtContentRun>().FirstOrDefault();
Run xRun = xContentRun.Descendants<Run>().FirstOrDefault();
Text xText = xRun.Descendants<Text>().FirstOrDefault();
string sdtTitle = alias.Val.Value;
switch (sdtTitle)
{
case "Name":
xText.Text = "Whatever";
break;
case "Age":
xText.Text = "69";
break;
}
}
}