【问题标题】:Finding a Content Control in Word based on Tagname根据标记名在 Word 中查找内容控件
【发布时间】:2011-10-12 13:25:02
【问题描述】:

我目前正在使用 OpenXml 尝试一些新事物,但最近遇到了一些麻烦。正如标题所说,我正在尝试使用 Xml 将数据动态插入到表中。为了在我的 Worddoc 中识别表格,我在其周围放置了富文本内容控件。

在我尝试在文档中搜索富文本内容控件的标记名之前,一切正常且看起来很好。在运行我的代码时,我不断收到“对象引用未设置为对象的实例。”。

他就是发生的那一行:

SdtBlock ccWithTable = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == t.Name).Single();

我使用以下 MSDN 文档尝试实现我的目标,但没有成功:

Inserting Repeating Data Items into a Word 2007 Table by Using the Open Xml API

如果有人可以帮助我,我会爱你很久。

【问题讨论】:

    标签: c# linq openxml


    【解决方案1】:

    好的,我创建了一个实际上效果更好的工作区。

    首先我从文档中检索所有表格..

    List<Table> tables = mainPart.Document.Body.Descendants<Table>().ToList();
    

    然后我检查作为我的表的父级的 SdtBlock 的标记参数,看看它们是否匹配。

    for (int f = 0; f < tables.Count; f++)
     {
       // If a table is found in the correct Content Control, fill it up with the data
       if (tables.ElementAt(f).Parent.Parent.GetFirstChild<SdtProperties>().GetFirstChild<Tag>().Val == t.Name)
         { //the rest of your code...
    

    t.Name 是我要查找的内容的标签。

    我实际上对这个结果很满意,因为这解决了几个相同的表(在同一个文档中,具有相同的标签)无法填充的事实。

    小旁注:如果您的文档中有其他非动态表格,最好尝试捕捉 if。

    tables.ElementAt(f).Parent.Parent.GetFirstChild<SdtProperties>().GetFirstChild<Tag>().Val 
    

    会杀了那些人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      相关资源
      最近更新 更多