Aspose::Words::Tables::Cell Class Reference

Detailed Description

Represents a table cell.

Cell can only be a child of a Row.

Cell can contain block-level nodes Paragraph and Table.

A minimal valid cell needs to have at least one Paragraph.

Examples

Shows how to create a table.

auto doc = MakeObject<Document>();
auto table = MakeObject<Table>(doc);
doc->get_FirstSection()->get_Body()->AppendChild(table);
// Tables contain rows, which contain cells, which may have paragraphs
// with typical elements such as runs, shapes, and even other tables.
// Calling the "EnsureMinimum" method on a table will ensure that
// the table has at least one row, cell, and paragraph.
auto firstRow = MakeObject<Row>(doc);
table->AppendChild(firstRow);
auto firstCell = MakeObject<Cell>(doc);
firstRow->AppendChild(firstCell);
auto paragraph = MakeObject<Paragraph>(doc);
firstCell->AppendChild(paragraph);
// Add text to the first call in the first row of the table.
auto run = MakeObject<Run>(doc, u"Hello world!");
paragraph->AppendChild(run);
doc->Save(ArtifactsDir + u"Table.CreateTable.docx");

Shows how to iterate through all tables in the document and print the contents of each cell.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
SharedPtr<TableCollection> tables = doc->get_FirstSection()->get_Body()->get_Tables();
ASSERT_EQ(2, tables->ToArray()->get_Length());
for (int i = 0; i < tables->get_Count(); i++)
{
std::cout << "Start of Table " << i << std::endl;
SharedPtr<RowCollection> rows = tables->idx_get(i)->get_Rows();
// We can use the "ToArray" method on a row collection to clone it into an array.
ASPOSE_ASSERT_EQ(rows, rows->ToArray());
ASPOSE_ASSERT_NS(rows, rows->ToArray());
for (int j = 0; j < rows->get_Count(); j++)
{
std::cout << "\tStart of Row " << j << std::endl;
SharedPtr<CellCollection> cells = rows->idx_get(j)->get_Cells();
// We can use the "ToArray" method on a cell collection to clone it into an array.
ASPOSE_ASSERT_EQ(cells, cells->ToArray());
ASPOSE_ASSERT_NS(cells, cells->ToArray());
for (int k = 0; k < cells->get_Count(); k++)
{
String cellText = cells->idx_get(k)->ToString(SaveFormat::Text).Trim();
std::cout << "\t\tContents of Cell:" << k << " = \"" << cellText << "\"" << std::endl;
}
std::cout << "\tEnd of Row " << j << std::endl;
}
std::cout << "End of Table " << i << "\n" << std::endl;
}

Shows how to build a nested table without using a document builder.

void CreateNestedTable()
{
auto doc = MakeObject<Document>();
// Create the outer table with three rows and four columns, and then add it to the document.
SharedPtr<Table> outerTable = CreateTable(doc, 3, 4, u"Outer Table");
doc->get_FirstSection()->get_Body()->AppendChild(outerTable);
// Create another table with two rows and two columns and then insert it into the first table's first cell.
SharedPtr<Table> innerTable = CreateTable(doc, 2, 2, u"Inner Table");
outerTable->get_FirstRow()->get_FirstCell()->AppendChild(innerTable);
doc->Save(ArtifactsDir + u"Table.CreateNestedTable.docx");
}
static SharedPtr<Table> CreateTable(SharedPtr<Document> doc, int rowCount, int cellCount, String cellText)
{
auto table = MakeObject<Table>(doc);
for (int rowId = 1; rowId <= rowCount; rowId++)
{
auto row = MakeObject<Row>(doc);
table->AppendChild(row);
for (int cellId = 1; cellId <= cellCount; cellId++)
{
auto cell = MakeObject<Cell>(doc);
cell->AppendChild(MakeObject<Paragraph>(doc));
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, cellText));
row->AppendChild(cell);
}
}
// You can use the "Title" and "Description" properties to add a title and description respectively to your table.
// The table must have at least one row before we can use these properties.
// These properties are meaningful for ISO / IEC 29500 compliant .docx documents (see the OoxmlCompliance class).
// If we save the document to pre-ISO/IEC 29500 formats, Microsoft Word ignores these properties.
table->set_Title(u"Aspose table title");
table->set_Description(u"Aspose table description");
return table;
}

#include <Aspose.Words.Cpp/Tables/Cell.h>

+ Inheritance diagram for Aspose::Words::Tables::Cell:

Public Member Functions

 Cell (const SharedPtr< DocumentBase > &doc)
 Initializes a new instance of the Cell class. More...
 
bool Accept (SharedPtr< DocumentVisitor > visitor) override
 Accepts a visitor. More...
 
void EnsureMinimum ()
 If the last child is not a paragraph, creates and appends one empty paragraph. More...
 
SharedPtr< CellFormatget_CellFormat ()
 Provides access to the formatting properties of the cell. More...
 
SharedPtr< Paragraphget_FirstParagraph ()
 Gets the first paragraph among the immediate children. More...
 
bool get_IsFirstCell ()
 True if this is the first cell inside a row; false otherwise. More...
 
bool get_IsLastCell ()
 True if this is the last cell inside a row; false otherwise. More...
 
SharedPtr< Paragraphget_LastParagraph ()
 Gets the last paragraph among the immediate children. More...
 
NodeType get_NodeType () const override
 Returns NodeType.Cell. More...
 
SharedPtr< ParagraphCollectionget_Paragraphs ()
 Gets a collection of paragraphs that are immediate children of the cell. More...
 
SharedPtr< Rowget_ParentRow ()
 Returns the parent row of the cell. More...
 
SharedPtr< TableCollectionget_Tables ()
 Gets a collection of tables that are immediate children of the cell. More...
 
virtual const TypeInfoGetType () const override
 
virtual bool Is (const TypeInfo &target) const override
 
- Public Member Functions inherited from CompositeNode
SharedPtr< NodeAppendChild (const SharedPtr< Node > &newChild)
 Adds the specified node to the end of the list of child nodes for this node. More...
 
SharedPtr< NodeCollectionget_ChildNodes ()
 Gets all immediate child nodes of this node. More...
 
int32_t get_Count ()
 Gets the number of immediate children of this node. More...
 
SharedPtr< Nodeget_FirstChild () const
 Gets the first child of the node. More...
 
bool get_HasChildNodes ()
 Returns true if this node has any child nodes. More...
 
bool get_IsComposite () override
 Returns true as this node can have child nodes. More...
 
SharedPtr< Nodeget_LastChild () const
 Gets the last child of the node. More...
 
SharedPtr< NodeGetChild (NodeType nodeType, int32_t index, bool isDeep)
 Returns an Nth child node that matches the specified type. More...
 
SharedPtr< NodeCollectionGetChildNodes (NodeType nodeType, bool isDeep)
 Returns a live collection of child nodes that match the specified type. More...
 
SharedPtr< IEnumerator< SharedPtr< Node > > > GetEnumerator () override
 Provides support for the for each style iteration over the child nodes of this node. More...
 
String GetText () override
 Gets the text of this node and of all its children. More...
 
int32_t IndexOf (const SharedPtr< Node > &child)
 Returns the index of the specified child node in the child node array. More...
 
SharedPtr< NodeInsertAfter (const SharedPtr< Node > &newChild, const SharedPtr< Node > &refChild)
 Inserts the specified node immediately after the specified reference node. More...
 
SharedPtr< NodeInsertBefore (const SharedPtr< Node > &newChild, const SharedPtr< Node > &refChild)
 Inserts the specified node immediately before the specified reference node. More...
 
SharedPtr< NodePrependChild (const SharedPtr< Node > &newChild)
 Adds the specified node to the beginning of the list of child nodes for this node. More...
 
void RemoveAllChildren ()
 Removes all the child nodes of the current node. More...
 
SharedPtr< NodeRemoveChild (const SharedPtr< Node > &oldChild)
 Removes the specified child node. More...
 
void RemoveSmartTags ()
 Removes all SmartTag descendant nodes of the current node. More...
 
SharedPtr< NodeListSelectNodes (const String &xpath)
 Selects a list of nodes matching the XPath expression. More...
 
SharedPtr< NodeSelectSingleNode (const String &xpath)
 Selects the first Node that matches the XPath expression. More...
 
- Public Member Functions inherited from Node
SharedPtr< NodeClone (bool isCloneChildren)
 Creates a duplicate of the node. More...
 
int32_t get_CustomNodeId () const
 Specifies custom node identifier. More...
 
virtual SharedPtr< DocumentBaseget_Document () const
 Gets the document to which this node belongs. More...
 
SharedPtr< Nodeget_NextSibling ()
 Gets the node immediately following this node. More...
 
SharedPtr< CompositeNodeget_ParentNode ()
 Gets the immediate parent of this node. More...
 
SharedPtr< Nodeget_PreviousSibling ()
 Gets the node immediately preceding this node. More...
 
SharedPtr< Rangeget_Range ()
 Returns a Range object that represents the portion of a document that is contained in this node. More...
 
SharedPtr< CompositeNodeGetAncestor (NodeType ancestorType)
 Gets the first ancestor of the specified NodeType. More...
 
template<typename T >
GetAncestorOf ()
 
SharedPtr< NodeNextPreOrder (const SharedPtr< Node > &rootNode)
 Gets next node according to the pre-order tree traversal algorithm. More...
 
SharedPtr< NodePreviousPreOrder (const SharedPtr< Node > &rootNode)
 Gets the previous node according to the pre-order tree traversal algorithm. More...
 
void Remove ()
 Removes itself from the parent. More...
 
void set_CustomNodeId (int32_t value)
 Setter for get_CustomNodeId. More...
 
String ToString (SaveFormat saveFormat)
 Exports the content of the node into a string in the specified format. More...
 
String ToString (const SharedPtr< SaveOptions > &saveOptions)
 Exports the content of the node into a string using the specified save options. More...
 

Static Public Member Functions

static const TypeInfoType ()
 
- Static Public Member Functions inherited from CompositeNode
static const TypeInfoType ()
 
- Static Public Member Functions inherited from Node
static String NodeTypeToString (NodeType nodeType)
 A utility method that converts a node type enum value into a user friendly string. More...
 
static const TypeInfoType ()
 

Constructor & Destructor Documentation

◆ Cell()

Aspose::Words::Tables::Cell::Cell ( const System::SharedPtr< Aspose::Words::DocumentBase > &  doc)

Initializes a new instance of the Cell class.

When Cell is created, it belongs to the specified document, but is not yet part of the document and ParentNode is null.

To append Cell to the document use InsertAfter or InsertBefore on the row where you want the cell inserted.

Parameters
docThe owner document.
Examples

Shows how to build a nested table without using a document builder.

void CreateNestedTable()
{
auto doc = MakeObject<Document>();
// Create the outer table with three rows and four columns, and then add it to the document.
SharedPtr<Table> outerTable = CreateTable(doc, 3, 4, u"Outer Table");
doc->get_FirstSection()->get_Body()->AppendChild(outerTable);
// Create another table with two rows and two columns and then insert it into the first table's first cell.
SharedPtr<Table> innerTable = CreateTable(doc, 2, 2, u"Inner Table");
outerTable->get_FirstRow()->get_FirstCell()->AppendChild(innerTable);
doc->Save(ArtifactsDir + u"Table.CreateNestedTable.docx");
}
static SharedPtr<Table> CreateTable(SharedPtr<Document> doc, int rowCount, int cellCount, String cellText)
{
auto table = MakeObject<Table>(doc);
for (int rowId = 1; rowId <= rowCount; rowId++)
{
auto row = MakeObject<Row>(doc);
table->AppendChild(row);
for (int cellId = 1; cellId <= cellCount; cellId++)
{
auto cell = MakeObject<Cell>(doc);
cell->AppendChild(MakeObject<Paragraph>(doc));
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, cellText));
row->AppendChild(cell);
}
}
// You can use the "Title" and "Description" properties to add a title and description respectively to your table.
// The table must have at least one row before we can use these properties.
// These properties are meaningful for ISO / IEC 29500 compliant .docx documents (see the OoxmlCompliance class).
// If we save the document to pre-ISO/IEC 29500 formats, Microsoft Word ignores these properties.
table->set_Title(u"Aspose table title");
table->set_Description(u"Aspose table description");
return table;
}

Member Function Documentation

◆ Accept()

bool Aspose::Words::Tables::Cell::Accept ( System::SharedPtr< Aspose::Words::DocumentVisitor visitor)
overridevirtual

Accepts a visitor.

Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

For more info see the Visitor design pattern.

Parameters
visitorThe visitor that will visit the nodes.
Returns
True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.
Examples

Shows how to print the node structure of every table in a document.

void TableToText()
{
auto doc = MakeObject<Document>(MyDir + u"DocumentVisitor-compatible features.docx");
auto visitor = MakeObject<ExDocumentVisitor::TableStructurePrinter>();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc->Accept(visitor);
std::cout << visitor->GetText() << std::endl;
}
class TableStructurePrinter : public DocumentVisitor
{
public:
TableStructurePrinter() : mVisitorIsInsideTable(false), mDocTraversalDepth(0)
{
mVisitedTables = MakeObject<System::Text::StringBuilder>();
mVisitorIsInsideTable = false;
}
String GetText()
{
return mVisitedTables->ToString();
}
VisitorAction VisitRun(SharedPtr<Run> run) override
{
if (mVisitorIsInsideTable)
{
IndentAndAppendLine(String(u"[Run] \"") + run->GetText() + u"\"");
}
}
VisitorAction VisitTableStart(SharedPtr<Table> table) override
{
int rows = 0;
int columns = 0;
if (table->get_Rows()->get_Count() > 0)
{
rows = table->get_Rows()->get_Count();
columns = table->get_FirstRow()->get_Count();
}
IndentAndAppendLine(String(u"[Table start] Size: ") + rows + u"x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
}
VisitorAction VisitTableEnd(SharedPtr<Table> table) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Table end]");
mVisitorIsInsideTable = false;
}
VisitorAction VisitRowStart(SharedPtr<Row> row) override
{
String rowContents = row->GetText().TrimEnd(MakeArray<char16_t>({u'\x0007', u' '})).Replace(u"\u0007", u", ");
int rowWidth = row->IndexOf(row->get_LastCell()) + 1;
int rowIndex = row->get_ParentTable()->IndexOf(row);
String rowStatusInTable = row->get_IsFirstRow() && row->get_IsLastRow() ? u"only"
: row->get_IsFirstRow() ? u"first"
: row->get_IsLastRow() ? String(u"last")
: String(u"");
if (rowStatusInTable != u"")
{
rowStatusInTable = String::Format(u", the {0} row in this table,", rowStatusInTable);
}
IndentAndAppendLine(String::Format(u"[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
}
VisitorAction VisitRowEnd(SharedPtr<Row> row) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Row end]");
}
VisitorAction VisitCellStart(SharedPtr<Cell> cell) override
{
SharedPtr<Row> row = cell->get_ParentRow();
SharedPtr<Table> table = row->get_ParentTable();
String cellStatusInRow = cell->get_IsFirstCell() && cell->get_IsLastCell() ? u"only"
: cell->get_IsFirstCell() ? u"first"
: cell->get_IsLastCell() ? String(u"last")
: String(u"");
if (cellStatusInRow != u"")
{
cellStatusInRow = String::Format(u", the {0} cell in this row", cellStatusInRow);
}
IndentAndAppendLine(String::Format(u"[Cell start] Row {0}, Col {1}{2}", table->IndexOf(row) + 1, row->IndexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
}
VisitorAction VisitCellEnd(SharedPtr<Cell> cell) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Cell end]");
}
private:
bool mVisitorIsInsideTable;
int mDocTraversalDepth;
SharedPtr<System::Text::StringBuilder> mVisitedTables;
void IndentAndAppendLine(String text)
{
for (int i = 0; i < mDocTraversalDepth; i++)
{
mVisitedTables->Append(u"| ");
}
mVisitedTables->AppendLine(text);
}
};

Implements Aspose::Words::Node.

◆ EnsureMinimum()

void Aspose::Words::Tables::Cell::EnsureMinimum ( )

If the last child is not a paragraph, creates and appends one empty paragraph.

Examples

Shows how to ensure a cell node contains the nodes we need to begin adding content to it.

auto doc = MakeObject<Document>();
auto table = MakeObject<Table>(doc);
doc->get_FirstSection()->get_Body()->AppendChild(table);
auto row = MakeObject<Row>(doc);
table->AppendChild(row);
auto cell = MakeObject<Cell>(doc);
row->AppendChild(cell);
// Cells may contain paragraphs with typical elements such as runs, shapes, and even other tables.
// Our new cell does not have any paragraphs, and we cannot add contents such as run and shape nodes to it until it does.
ASSERT_EQ(0, cell->GetChildNodes(NodeType::Any, true)->get_Count());
// Calling the "EnsureMinimum" method on a cell will ensure that
// the cell has at least one empty paragraph, which we can then add contents to.
cell->EnsureMinimum();
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Hello world!"));

◆ get_CellFormat()

System::SharedPtr<Aspose::Words::Tables::CellFormat> Aspose::Words::Tables::Cell::get_CellFormat ( )

Provides access to the formatting properties of the cell.

Examples

Shows how to modify the format of rows and cells in a table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"City");
builder->InsertCell();
builder->Write(u"Country");
builder->EndRow();
builder->InsertCell();
builder->Write(u"London");
builder->InsertCell();
builder->Write(u"U.K.");
builder->EndTable();
// Use the first row's "RowFormat" property to modify the formatting
// of the contents of all cells in this row.
SharedPtr<RowFormat> rowFormat = table->get_FirstRow()->get_RowFormat();
rowFormat->set_Height(25);
rowFormat->get_Borders()->idx_get(BorderType::Bottom)->set_Color(System::Drawing::Color::get_Red());
// Use the "CellFormat" property of the first cell in the last row to modify the formatting of that cell's contents.
SharedPtr<CellFormat> cellFormat = table->get_LastRow()->get_FirstCell()->get_CellFormat();
cellFormat->set_Width(100);
cellFormat->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_Orange());
doc->Save(ArtifactsDir + u"Table.RowCellFormat.docx");

Shows how to modify formatting of a table cell.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
SharedPtr<Table> table = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
SharedPtr<Cell> firstCell = table->get_FirstRow()->get_FirstCell();
// Use a cell's "CellFormat" property to set formatting that modifies the appearance of that cell.
firstCell->get_CellFormat()->set_Width(30);
firstCell->get_CellFormat()->set_Orientation(TextOrientation::Downward);
firstCell->get_CellFormat()->get_Shading()->set_ForegroundPatternColor(System::Drawing::Color::get_LightGreen());
doc->Save(ArtifactsDir + u"Table.CellFormat.docx");

Shows how to combine the rows from two tables into one.

auto doc = MakeObject<Document>(MyDir + u"Tables.docx");
// Below are two ways of getting a table from a document.
// 1 - From the "Tables" collection of a Body node:
SharedPtr<Table> firstTable = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
// 2 - Using the "GetChild" method:
auto secondTable = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 1, true));
// Append all rows from the current table to the next.
while (secondTable->get_HasChildNodes())
{
firstTable->get_Rows()->Add(secondTable->get_FirstRow());
}
// Remove the empty table container.
secondTable->Remove();
doc->Save(ArtifactsDir + u"Table.CombineTables.docx");

◆ get_FirstParagraph()

System::SharedPtr<Aspose::Words::Paragraph> Aspose::Words::Tables::Cell::get_FirstParagraph ( )

Gets the first paragraph among the immediate children.

Examples

Shows how to create a nested table using a document builder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Build the outer table.
SharedPtr<Cell> cell = builder->InsertCell();
builder->Writeln(u"Outer Table Cell 1");
builder->InsertCell();
builder->Writeln(u"Outer Table Cell 2");
builder->EndTable();
// Move to the first cell of the outer table, the build another table inside the cell.
builder->MoveTo(cell->get_FirstParagraph());
builder->InsertCell();
builder->Writeln(u"Inner Table Cell 1");
builder->InsertCell();
builder->Writeln(u"Inner Table Cell 2");
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertNestedTable.docx");

Shows how to build a nested table without using a document builder.

void CreateNestedTable()
{
auto doc = MakeObject<Document>();
// Create the outer table with three rows and four columns, and then add it to the document.
SharedPtr<Table> outerTable = CreateTable(doc, 3, 4, u"Outer Table");
doc->get_FirstSection()->get_Body()->AppendChild(outerTable);
// Create another table with two rows and two columns and then insert it into the first table's first cell.
SharedPtr<Table> innerTable = CreateTable(doc, 2, 2, u"Inner Table");
outerTable->get_FirstRow()->get_FirstCell()->AppendChild(innerTable);
doc->Save(ArtifactsDir + u"Table.CreateNestedTable.docx");
}
static SharedPtr<Table> CreateTable(SharedPtr<Document> doc, int rowCount, int cellCount, String cellText)
{
auto table = MakeObject<Table>(doc);
for (int rowId = 1; rowId <= rowCount; rowId++)
{
auto row = MakeObject<Row>(doc);
table->AppendChild(row);
for (int cellId = 1; cellId <= cellCount; cellId++)
{
auto cell = MakeObject<Cell>(doc);
cell->AppendChild(MakeObject<Paragraph>(doc));
cell->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, cellText));
row->AppendChild(cell);
}
}
// You can use the "Title" and "Description" properties to add a title and description respectively to your table.
// The table must have at least one row before we can use these properties.
// These properties are meaningful for ISO / IEC 29500 compliant .docx documents (see the OoxmlCompliance class).
// If we save the document to pre-ISO/IEC 29500 formats, Microsoft Word ignores these properties.
table->set_Title(u"Aspose table title");
table->set_Description(u"Aspose table description");
return table;
}

◆ get_IsFirstCell()

bool Aspose::Words::Tables::Cell::get_IsFirstCell ( )

True if this is the first cell inside a row; false otherwise.

Examples

Shows how to print the node structure of every table in a document.

void TableToText()
{
auto doc = MakeObject<Document>(MyDir + u"DocumentVisitor-compatible features.docx");
auto visitor = MakeObject<ExDocumentVisitor::TableStructurePrinter>();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc->Accept(visitor);
std::cout << visitor->GetText() << std::endl;
}
class TableStructurePrinter : public DocumentVisitor
{
public:
TableStructurePrinter() : mVisitorIsInsideTable(false), mDocTraversalDepth(0)
{
mVisitedTables = MakeObject<System::Text::StringBuilder>();
mVisitorIsInsideTable = false;
}
String GetText()
{
return mVisitedTables->ToString();
}
VisitorAction VisitRun(SharedPtr<Run> run) override
{
if (mVisitorIsInsideTable)
{
IndentAndAppendLine(String(u"[Run] \"") + run->GetText() + u"\"");
}
}
VisitorAction VisitTableStart(SharedPtr<Table> table) override
{
int rows = 0;
int columns = 0;
if (table->get_Rows()->get_Count() > 0)
{
rows = table->get_Rows()->get_Count();
columns = table->get_FirstRow()->get_Count();
}
IndentAndAppendLine(String(u"[Table start] Size: ") + rows + u"x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
}
VisitorAction VisitTableEnd(SharedPtr<Table> table) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Table end]");
mVisitorIsInsideTable = false;
}
VisitorAction VisitRowStart(SharedPtr<Row> row) override
{
String rowContents = row->GetText().TrimEnd(MakeArray<char16_t>({u'\x0007', u' '})).Replace(u"\u0007", u", ");
int rowWidth = row->IndexOf(row->get_LastCell()) + 1;
int rowIndex = row->get_ParentTable()->IndexOf(row);
String rowStatusInTable = row->get_IsFirstRow() && row->get_IsLastRow() ? u"only"
: row->get_IsFirstRow() ? u"first"
: row->get_IsLastRow() ? String(u"last")
: String(u"");
if (rowStatusInTable != u"")
{
rowStatusInTable = String::Format(u", the {0} row in this table,", rowStatusInTable);
}
IndentAndAppendLine(String::Format(u"[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
}
VisitorAction VisitRowEnd(SharedPtr<Row> row) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Row end]");
}
VisitorAction VisitCellStart(SharedPtr<Cell> cell) override
{
SharedPtr<Row> row = cell->get_ParentRow();
SharedPtr<Table> table = row->get_ParentTable();
String cellStatusInRow = cell->get_IsFirstCell() && cell->get_IsLastCell() ? u"only"
: cell->get_IsFirstCell() ? u"first"
: cell->get_IsLastCell() ? String(u"last")
: String(u"");
if (cellStatusInRow != u"")
{
cellStatusInRow = String::Format(u", the {0} cell in this row", cellStatusInRow);
}
IndentAndAppendLine(String::Format(u"[Cell start] Row {0}, Col {1}{2}", table->IndexOf(row) + 1, row->IndexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
}
VisitorAction VisitCellEnd(SharedPtr<Cell> cell) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Cell end]");
}
private:
bool mVisitorIsInsideTable;
int mDocTraversalDepth;
SharedPtr<System::Text::StringBuilder> mVisitedTables;
void IndentAndAppendLine(String text)
{
for (int i = 0; i < mDocTraversalDepth; i++)
{
mVisitedTables->Append(u"| ");
}
mVisitedTables->AppendLine(text);
}
};

◆ get_IsLastCell()

bool Aspose::Words::Tables::Cell::get_IsLastCell ( )

True if this is the last cell inside a row; false otherwise.

Examples

Shows how to print the node structure of every table in a document.

void TableToText()
{
auto doc = MakeObject<Document>(MyDir + u"DocumentVisitor-compatible features.docx");
auto visitor = MakeObject<ExDocumentVisitor::TableStructurePrinter>();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc->Accept(visitor);
std::cout << visitor->GetText() << std::endl;
}
class TableStructurePrinter : public DocumentVisitor
{
public:
TableStructurePrinter() : mVisitorIsInsideTable(false), mDocTraversalDepth(0)
{
mVisitedTables = MakeObject<System::Text::StringBuilder>();
mVisitorIsInsideTable = false;
}
String GetText()
{
return mVisitedTables->ToString();
}
VisitorAction VisitRun(SharedPtr<Run> run) override
{
if (mVisitorIsInsideTable)
{
IndentAndAppendLine(String(u"[Run] \"") + run->GetText() + u"\"");
}
}
VisitorAction VisitTableStart(SharedPtr<Table> table) override
{
int rows = 0;
int columns = 0;
if (table->get_Rows()->get_Count() > 0)
{
rows = table->get_Rows()->get_Count();
columns = table->get_FirstRow()->get_Count();
}
IndentAndAppendLine(String(u"[Table start] Size: ") + rows + u"x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
}
VisitorAction VisitTableEnd(SharedPtr<Table> table) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Table end]");
mVisitorIsInsideTable = false;
}
VisitorAction VisitRowStart(SharedPtr<Row> row) override
{
String rowContents = row->GetText().TrimEnd(MakeArray<char16_t>({u'\x0007', u' '})).Replace(u"\u0007", u", ");
int rowWidth = row->IndexOf(row->get_LastCell()) + 1;
int rowIndex = row->get_ParentTable()->IndexOf(row);
String rowStatusInTable = row->get_IsFirstRow() && row->get_IsLastRow() ? u"only"
: row->get_IsFirstRow() ? u"first"
: row->get_IsLastRow() ? String(u"last")
: String(u"");
if (rowStatusInTable != u"")
{
rowStatusInTable = String::Format(u", the {0} row in this table,", rowStatusInTable);
}
IndentAndAppendLine(String::Format(u"[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
}
VisitorAction VisitRowEnd(SharedPtr<Row> row) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Row end]");
}
VisitorAction VisitCellStart(SharedPtr<Cell> cell) override
{
SharedPtr<Row> row = cell->get_ParentRow();
SharedPtr<Table> table = row->get_ParentTable();
String cellStatusInRow = cell->get_IsFirstCell() && cell->get_IsLastCell() ? u"only"
: cell->get_IsFirstCell() ? u"first"
: cell->get_IsLastCell() ? String(u"last")
: String(u"");
if (cellStatusInRow != u"")
{
cellStatusInRow = String::Format(u", the {0} cell in this row", cellStatusInRow);
}
IndentAndAppendLine(String::Format(u"[Cell start] Row {0}, Col {1}{2}", table->IndexOf(row) + 1, row->IndexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
}
VisitorAction VisitCellEnd(SharedPtr<Cell> cell) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Cell end]");
}
private:
bool mVisitorIsInsideTable;
int mDocTraversalDepth;
SharedPtr<System::Text::StringBuilder> mVisitedTables;
void IndentAndAppendLine(String text)
{
for (int i = 0; i < mDocTraversalDepth; i++)
{
mVisitedTables->Append(u"| ");
}
mVisitedTables->AppendLine(text);
}
};

◆ get_LastParagraph()

System::SharedPtr<Aspose::Words::Paragraph> Aspose::Words::Tables::Cell::get_LastParagraph ( )

Gets the last paragraph among the immediate children.

Examples

Shows how to apply settings to vertical borders to a table row's format.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a table with red and blue inner borders.
SharedPtr<Table> table = builder->StartTable();
for (int i = 0; i < 3; i++)
{
builder->InsertCell();
builder->Write(String::Format(u"Row {0}, Column 1", i + 1));
builder->InsertCell();
builder->Write(String::Format(u"Row {0}, Column 2", i + 1));
SharedPtr<Row> row = builder->EndRow();
SharedPtr<BorderCollection> borders = row->get_RowFormat()->get_Borders();
// Adjust the appearance of borders that will appear between rows.
borders->get_Horizontal()->set_Color(System::Drawing::Color::get_Red());
borders->get_Horizontal()->set_LineStyle(LineStyle::Dot);
borders->get_Horizontal()->set_LineWidth(2.0);
// Adjust the appearance of borders that will appear between cells.
borders->get_Vertical()->set_Color(System::Drawing::Color::get_Blue());
borders->get_Vertical()->set_LineStyle(LineStyle::Dot);
borders->get_Vertical()->set_LineWidth(2.0);
}
// A row format, and a cell's inner paragraph use different border settings.
SharedPtr<Border> border = table->get_FirstRow()->get_FirstCell()->get_LastParagraph()->get_ParagraphFormat()->get_Borders()->get_Vertical();
ASSERT_EQ(System::Drawing::Color::Empty.ToArgb(), border->get_Color().ToArgb());
ASPOSE_ASSERT_EQ(0.0, border->get_LineWidth());
ASSERT_EQ(LineStyle::None, border->get_LineStyle());
doc->Save(ArtifactsDir + u"Border.VerticalBorders.docx");

◆ get_NodeType()

Aspose::Words::NodeType Aspose::Words::Tables::Cell::get_NodeType ( ) const
overridevirtual

Returns NodeType.Cell.

Examples

Shows how to traverse a composite node's tree of child nodes.

void RecurseChildren()
{
auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
ASSERT_TRUE(doc->get_IsComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
TraverseAllNodes(doc, 0);
}
void TraverseAllNodes(SharedPtr<CompositeNode> parentNode, int depth)
{
for (SharedPtr<Node> childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
std::cout << (String(u'\t', depth)) << Node::NodeTypeToString(childNode->get_NodeType());
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode->get_IsComposite())
{
std::cout << std::endl;
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode), depth + 1);
}
else if (System::ObjectExt::Is<Inline>(childNode))
{
std::cout << " - \"" << childNode->GetText().Trim() << "\"" << std::endl;
}
else
{
std::cout << std::endl;
}
}
}

Implements Aspose::Words::Node.

◆ get_Paragraphs()

System::SharedPtr<Aspose::Words::ParagraphCollection> Aspose::Words::Tables::Cell::get_Paragraphs ( )

Gets a collection of paragraphs that are immediate children of the cell.

Examples

Shows how to set a table to stay together on the same page.

auto doc = MakeObject<Document>(MyDir + u"Table spanning two pages.docx");
SharedPtr<Table> table = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
// Enabling KeepWithNext for every paragraph in the table except for the
// last ones in the last row will prevent the table from splitting across multiple pages.
for (const auto& cell : System::IterateOver(table->GetChildNodes(NodeType::Cell, true)->LINQ_OfType<SharedPtr<Cell>>()))
{
for (const auto& para : System::IterateOver(cell->get_Paragraphs()->LINQ_OfType<SharedPtr<Paragraph>>()))
{
ASSERT_TRUE(para->get_IsInCell());
if (!(cell->get_ParentRow()->get_IsLastRow() && para->get_IsEndOfCell()))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
}
}
doc->Save(ArtifactsDir + u"Table.KeepTableTogether.docx");

◆ get_ParentRow()

System::SharedPtr<Aspose::Words::Tables::Row> Aspose::Words::Tables::Cell::get_ParentRow ( )

Returns the parent row of the cell.

Examples

Shows how to set a table to stay together on the same page.

auto doc = MakeObject<Document>(MyDir + u"Table spanning two pages.docx");
SharedPtr<Table> table = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
// Enabling KeepWithNext for every paragraph in the table except for the
// last ones in the last row will prevent the table from splitting across multiple pages.
for (const auto& cell : System::IterateOver(table->GetChildNodes(NodeType::Cell, true)->LINQ_OfType<SharedPtr<Cell>>()))
{
for (const auto& para : System::IterateOver(cell->get_Paragraphs()->LINQ_OfType<SharedPtr<Paragraph>>()))
{
ASSERT_TRUE(para->get_IsInCell());
if (!(cell->get_ParentRow()->get_IsLastRow() && para->get_IsEndOfCell()))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
}
}
doc->Save(ArtifactsDir + u"Table.KeepTableTogether.docx");

◆ get_Tables()

System::SharedPtr<Aspose::Words::Tables::TableCollection> Aspose::Words::Tables::Cell::get_Tables ( )

Gets a collection of tables that are immediate children of the cell.

Examples

Shows how to find out if a tables are nested.

void CalculateDepthOfNestedTables()
{
auto doc = MakeObject<Document>(MyDir + u"Nested tables.docx");
SharedPtr<NodeCollection> tables = doc->GetChildNodes(NodeType::Table, true);
for (int i = 0; i < tables->get_Count(); i++)
{
auto table = System::DynamicCast<Table>(tables->idx_get(i));
// Find out if any cells in the table have other tables as children.
int count = GetChildTableCount(table);
std::cout << "Table #" << i << " has " << count << " tables directly within its cells" << std::endl;
// Find out if the table is nested inside another table, and, if so, at what depth.
int tableDepth = GetNestedDepthOfTable(table);
if (tableDepth > 0)
{
std::cout << "Table #" << i << " is nested inside another table at depth of " << tableDepth << std::endl;
}
else
{
std::cout << "Table #" << i << " is a non nested table (is not a child of another table)" << std::endl;
}
}
}
static int GetNestedDepthOfTable(SharedPtr<Table> table)
{
int depth = 0;
SharedPtr<Node> parent = table->GetAncestor(table->get_NodeType());
while (parent != nullptr)
{
depth++;
parent = parent->GetAncestorOf<SharedPtr<Table>>();
}
return depth;
}
static int GetChildTableCount(SharedPtr<Table> table)
{
int childTableCount = 0;
for (const auto& row : System::IterateOver(table->get_Rows()->LINQ_OfType<SharedPtr<Row>>()))
{
for (const auto& Cell : System::IterateOver(row->get_Cells()->LINQ_OfType<SharedPtr<Cell>>()))
{
SharedPtr<TableCollection> childTables = Cell->get_Tables();
if (childTables->get_Count() > 0)
{
childTableCount++;
}
}
}
return childTableCount;
}

◆ GetType()

virtual const System::TypeInfo& Aspose::Words::Tables::Cell::GetType ( ) const
overridevirtual

Reimplemented from Aspose::Words::CompositeNode.

◆ Is()

virtual bool Aspose::Words::Tables::Cell::Is ( const System::TypeInfo target) const
overridevirtual

Reimplemented from Aspose::Words::CompositeNode.

◆ Type()

static const System::TypeInfo& Aspose::Words::Tables::Cell::Type ( )
static