TableCollection
内容
[
隐藏
]TableCollection class
提供对集合的类型访问Table节点.
要了解更多信息,请访问使用表格文档文章。
public class TableCollection : NodeCollection
特性
| 姓名 | 描述 | 
|---|---|
| Count { get; } | 获取集合中的节点数。 | 
| Item { get; } | 检索 Table在给定的索引处。 (2 indexers) | 
方法
| 姓名 | 描述 | 
|---|---|
| Add(Node) | 在集合末尾添加一个节点。 | 
| Clear() | 从此集合和文档中删除所有节点。 | 
| Contains(Node) | 确定节点是否在集合中。 | 
| GetEnumerator() | 提供对节点集合的简单“foreach”样式迭代。 | 
| IndexOf(Node) | 返回指定节点的从零开始的索引。 | 
| Insert(int, Node) | 将节点插入到指定索引的集合中。 | 
| Remove(Node) | 从集合和文档中删除节点。 | 
| RemoveAt(int) | 从集合和文档中删除指定索引处的节点。 | 
| ToArray() | 将集合中的所有表复制到新的表数组中。 (2 methods) | 
例子
展示如何删除文档中所有表格的第一行和最后一行。
Document doc = new Document(MyDir + "Tables.docx");
TableCollection tables = doc.FirstSection.Body.Tables;
Assert.AreEqual(5, tables[0].Rows.Count);
Assert.AreEqual(4, tables[1].Rows.Count);
foreach (Table table in tables.OfType<Table>())
{
    table.FirstRow?.Remove();
    table.LastRow?.Remove();
}
Assert.AreEqual(3, tables[0].Rows.Count);
Assert.AreEqual(2, tables[1].Rows.Count);
显示如何确定表是否嵌套。
public void CalculateDepthOfNestedTables()
{
    Document doc = new Document(MyDir + "Nested tables.docx");
    NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);
    for (int i = 0; i < tables.Count; i++)
    {
        Table table = (Table)tables[i];
        // 查明表格中是否有单元格具有其他表格作为子表格。
        int count = GetChildTableCount(table);
        Console.WriteLine("Table #{0} has {1} tables directly within its cells", i, count);
        // 查明表是否嵌套在另一个表中,如果是,则嵌套深度是多少。
        int tableDepth = GetNestedDepthOfTable(table);
        if (tableDepth > 0)
            Console.WriteLine("Table #{0} is nested inside another table at depth of {1}", i,
                tableDepth);
        else
            Console.WriteLine("Table #{0} is a non nested table (is not a child of another table)", i);
    }
}
/// <summary>
/// 计算一个表嵌套在其他表中的级别。
/// </summary>
/// <returns>
/// 一个整数,表示表的嵌套深度(父表节点的数量)。
/// </returns>
private static int GetNestedDepthOfTable(Table table)
{
    int depth = 0;
    Node parent = table.GetAncestor(table.NodeType);
    while (parent != null)
    {
        depth++;
        parent = parent.GetAncestor(typeof(Table));
    }
    return depth;
}
/// <summary>
/// 确定表的单元格内是否包含任何直接子表。
/// 不要递归遍历这些表来检查进一步的表。
/// </summary>
/// <returns>
/// 如果至少有一个子单元格包含表格,则返回 true。
/// 如果表格中没有单元格包含表格,则返回 false。
/// </returns>
private static int GetChildTableCount(Table table)
{
    int childTableCount = 0;
    foreach (Row row in table.Rows)
    {
        foreach (Cell Cell in row.Cells)
        {
            TableCollection childTables = Cell.Tables;
            if (childTables.Count > 0)
                childTableCount++;
        }
    }
    return childTableCount;
}
也可以看看
- class NodeCollection
- 命名空间 Aspose.Words.Tables
- 部件 Aspose.Words