Hi,
I am learning OpenXML. I have been looking for hours trying to find how to do a simple task: insert text into a content control in c#.
I have a template document with two controls "Name" and "Age." I can find them well enough, but I just cannot add text in them. I've tried a number of things, all to no avail.
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);
}
}
All help greatly appreciated.
Cheers,
Tim.
EDIT --
Thanks for the response. Taking your advice, I've attempted to cast and drilled down with the productivity tool to find the child elements to update. Could you tell me if you can see why this code is simply not writing anything to the document?
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;
}
}
}