代码之家  ›  专栏  ›  技术社区  ›  Jens

基于标记名在Word中查找内容控件

  •  1
  • Jens  · 技术社区  · 15 年前

    我目前正在用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

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

    1 回复  |  直到 13 年前
        1
  •  2
  •   Jens    15 年前

    好吧,我创造了一个更有效的工作场所。

    首先,我从文档中检索所有表。

    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 
    

    会杀了那些。