开发者

Programatically filling content controls in Word document (OpenXML) in .NET

I have a really simple word document with Content Controls (all text). I want to loop through the controls, filling them with values from a dictionary. Should be super simple, but something is wrong:

var myValues = new Dictionary<string, string>(); //And fill it

using (var wordDoc = WordprocessingDocument.Open(outputFile, true))
{
    MainDocumentPart mainPart = wordDoc.MainDocumentPart;

    foreach(SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
    {
      SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault开发者_JS百科();

      if (alias != null)
      {
          string sdtTitle = alias.Val.Value;
          sdt.??? = myValues[sdtTitle];
      }
    }
    mainPart.Document.Save();
 }

How do I write my value into the document? Do I need a CustomXmlPart?


If you are going to do something like that, you'll need to write suitable content into the Sdt's SdtContent: a paragraph or a run or a tc etc depending on the sdt's parent element.

The alternative is to put the contents of your dictionary into a CustomXml part, and set up databindings on each content control which refer to the relevant dictionary element. Word will then resolve the bindings when the docx is first opened (which is not much good to you if you expect your users to open it with something else).


You can use this code.

foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
{
SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();

if (alias != null)
 {
  string sdtTitle = alias.Val.Value;
  Text t = sdt.Descendants<Text>().First();
  t.Text = "test";
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜