Find a specific Table (after a bookmark) in open xml

穿精又带淫゛_ 提交于 2019-12-07 16:25:18

问题


I have a document with multiple tables in it. I need to fill some of those tables. The problem im having is how do i locate them? I can interate through them

var doc = document.MainDocumentPart.Document;
var tables= doc.Body.Elements< Table >();

But how do i find a specific table? The table can change so i cant rely on the order. I was thinking of placing a bookmark ahead of the specific table and just locate the first table after the bookmark, but i have failed to find out how to do that...

So, how do one find a specific table in a document?

If there is a better way of doing it please let me know.


回答1:


Give the tables captions.

First in Word, create the tables, and right click one of them, Table Properties, Alt Text, fill in the Title box, save, close.

Now in OpenXML, find the table with specific captions.

IEnumerable<TableProperties> tableProperties = bd.Descendants<TableProperties>().Where(tp => tp.TableCaption != null);
foreach(TableProperties tProp in tableProperties)
{
    if(tProp.TableCaption.Val.Equals("myCaption")) // see comment, this is actually StringValue
    {
        // do something for table with myCaption
        Table table = (Table) tProp.Parent;
    }
}



回答2:


This article describes a neat solution using Content Controls:

http://msdn.microsoft.com/en-us/library/cc197932(v=office.12).aspx




回答3:


A bit more elegant solution to this, using bookmarkstart as a locator would be

BookmarkStart bookmark = YourBookMarkStart;
OpenXmlElement elem = bookmark.First().Parent;
//isolate tabel
while (!(elem is DocumentFormat.OpenXml.Wordprocessing.Table))
    elem = elem.Parent;
var table = elem; //found



回答4:


I found a solution. It's not the prettiest solution i have come up with but it seems to work. At least on the documents that i have tried.

I create my table. Insert a Bookmark anywhere in the table and then find the bookmark.

var bookmarkStart = doc.Body.Descendants<BookmarkStart>().Where(r => r.Name == "tableBookmark");
if (bookmarkStart != null)
{
    var test  = bookmarkStart.First().Parent.Parent.Parent.Parent;
    if (test.GetType() == typeof (DocumentFormat.OpenXml.Wordprocessing.Table))
        myTable = (Table)test;
}

Please feel free to give me a better solution!!! :) For instance I'm probably going to make a recursive method that finds the tables instead of using Parent.Parent.Parent.Parent



来源:https://stackoverflow.com/questions/15520585/find-a-specific-table-after-a-bookmark-in-open-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!