public class Cell extends CompositeNode
To learn more, visit the Working with Tables documentation article.
Remarks:
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.
Document doc = new Document();
Table table = new Table(doc);
doc.getFirstSection().getBody().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.
Row firstRow = new Row(doc);
table.appendChild(firstRow);
Cell firstCell = new Cell(doc);
firstRow.appendChild(firstCell);
Paragraph paragraph = new Paragraph(doc);
firstCell.appendChild(paragraph);
// Add text to the first cell in the first row of the table.
Run run = new Run(doc, "Hello world!");
paragraph.appendChild(run);
doc.save(getArtifactsDir() + "Table.CreateTable.docx");
Shows how to iterate through all tables in the document and print the contents of each cell.
Document doc = new Document(getMyDir() + "Tables.docx");
TableCollection tables = doc.getFirstSection().getBody().getTables();
Assert.assertEquals(2, tables.toArray().length);
for (int i = 0; i < tables.getCount(); i++) {
System.out.println(MessageFormat.format("Start of Table {0}", i));
RowCollection rows = tables.get(i).getRows();
for (int j = 0; j < rows.getCount(); j++) {
System.out.println(MessageFormat.format("\tStart of Row {0}", j));
CellCollection cells = rows.get(j).getCells();
for (int k = 0; k < cells.getCount(); k++) {
String cellText = cells.get(k).toString(SaveFormat.TEXT).trim();
System.out.println(MessageFormat.format("\t\tContents of Cell:{0} = \"{1}\"", k, cellText));
}
System.out.println(MessageFormat.format("\tEnd of Row {0}", j));
}
System.out.println(MessageFormat.format("End of Table {0}\n", i));
}
Shows how to build a nested table without using a document builder.
public void createNestedTable() throws Exception {
Document doc = new Document();
// Create the outer table with three rows and four columns, and then add it to the document.
Table outerTable = createTable(doc, 3, 4, "Outer Table");
doc.getFirstSection().getBody().appendChild(outerTable);
// Create another table with two rows and two columns and then insert it into the first table's first cell.
Table innerTable = createTable(doc, 2, 2, "Inner Table");
outerTable.getFirstRow().getFirstCell().appendChild(innerTable);
doc.save(getArtifactsDir() + "Table.CreateNestedTable.docx");
}
// Creates a new table in the document with the given dimensions and text in each cell.
private Table createTable(final Document doc, final int rowCount, final int cellCount, final String cellText) throws Exception {
Table table = new Table(doc);
for (int rowId = 1; rowId <= rowCount; rowId++) {
Row row = new Row(doc);
table.appendChild(row);
for (int cellId = 1; cellId <= cellCount; cellId++) {
Cell cell = new Cell(doc);
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().appendChild(new 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.setTitle("Aspose table title");
table.setDescription("Aspose table description");
return table;
}
| Constructor and Description |
|---|
Cell(DocumentBase doc)
Initializes a new instance of the
Cell class. |
| Modifier and Type | Method and Description |
|---|---|
boolean |
accept(DocumentVisitor visitor)
Accepts a visitor.
|
int |
acceptEnd(DocumentVisitor visitor)
Accepts a visitor for visiting the end of the cell.
|
int |
acceptStart(DocumentVisitor visitor)
Accepts a visitor for visiting the start of the cell.
|
void |
clearCellAttrs() |
void |
ensureMinimum()
If the last child is not a paragraph, creates and appends one empty paragraph.
|
java.lang.Object |
fetchCellAttr(int key) |
java.lang.Object |
fetchInheritedCellAttr(int key) |
CellFormat |
getCellFormat()
Provides access to the formatting properties of the cell.
|
java.lang.Object |
getDirectCellAttr(int key) |
Paragraph |
getFirstParagraph()
Gets the first paragraph among the immediate children.
|
Paragraph |
getLastParagraph()
Gets the last paragraph among the immediate children.
|
Cell |
getNextCell()
Gets the next
Cell node. |
int |
getNodeType()
Returns
NodeType.CELL. |
ParagraphCollection |
getParagraphs()
Gets a collection of paragraphs that are immediate children of the cell.
|
Row |
getParentRow()
Returns the parent row of the cell.
|
Cell |
getPreviousCell()
Gets the previous
Cell node. |
TableCollection |
getTables()
Gets a collection of tables that are immediate children of the cell.
|
boolean |
isFirstCell()
True if this is the first cell inside a row; false otherwise.
|
boolean |
isLastCell()
True if this is the last cell inside a row; false otherwise.
|
void |
removeMoveRevisions() |
void |
setCellAttr(int key,
java.lang.Object value) |
acceptChildren, acceptCore, appendChild, coreRemoveSelfOnly, getChild, getChildNodes, getContainer, getCount, getCurrentNode, getFirstChild, getLastChild, getNextMatchingNode, getText, hasChildNodes, indexOf, insertAfter, insertBefore, isComposite, iterator, prependChild, removeAllChildren, removeChild, removeSmartTags, selectNodes, selectSingleNodedeepClone, getAncestor, getAncestor, getCustomNodeId, getDocument, getNextSibling, getParentNode, getPreviousSibling, getRange, memberwiseClone, nextPreOrder, nodeTypeToString, previousPreOrder, remove, setCustomNodeId, toString, toString, toString, visitorActionToBoolpublic Cell(DocumentBase doc)
Cell class.
Remarks:
When Cell is created, it belongs to the specified document, but is not yet part of the document and Node.getParentNode() is null.
To append Cell to the document use CompositeNode.insertAfter(com.aspose.words.Node, com.aspose.words.Node) or CompositeNode.insertBefore(com.aspose.words.Node, com.aspose.words.Node) on the row where you want the cell inserted.
Examples:
Shows how to build a nested table without using a document builder.
public void createNestedTable() throws Exception {
Document doc = new Document();
// Create the outer table with three rows and four columns, and then add it to the document.
Table outerTable = createTable(doc, 3, 4, "Outer Table");
doc.getFirstSection().getBody().appendChild(outerTable);
// Create another table with two rows and two columns and then insert it into the first table's first cell.
Table innerTable = createTable(doc, 2, 2, "Inner Table");
outerTable.getFirstRow().getFirstCell().appendChild(innerTable);
doc.save(getArtifactsDir() + "Table.CreateNestedTable.docx");
}
// Creates a new table in the document with the given dimensions and text in each cell.
private Table createTable(final Document doc, final int rowCount, final int cellCount, final String cellText) throws Exception {
Table table = new Table(doc);
for (int rowId = 1; rowId <= rowCount; rowId++) {
Row row = new Row(doc);
table.appendChild(row);
for (int cellId = 1; cellId <= cellCount; cellId++) {
Cell cell = new Cell(doc);
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().appendChild(new 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.setTitle("Aspose table title");
table.setDescription("Aspose table description");
return table;
}
doc - The owner document.public int getNodeType()
NodeType.CELL.
Examples:
Shows how to traverse a composite node's tree of child nodes.
public void recurseChildren() throws Exception {
Document doc = new Document(getMyDir() + "Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
Assert.assertTrue(doc.isComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
traverseAllNodes(doc, 0);
}
/// <summary>
/// Recursively traverses a node tree while printing the type of each node
/// with an indent depending on depth as well as the contents of all inline nodes.
/// </summary>
public void traverseAllNodes(CompositeNode parentNode, int depth) {
for (Node childNode = parentNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) {
System.out.println(MessageFormat.format("{0}{1}", String.format(" ", depth), Node.nodeTypeToString(childNode.getNodeType())));
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode.isComposite()) {
System.out.println();
traverseAllNodes((CompositeNode) childNode, depth + 1);
} else if (childNode instanceof Inline) {
System.out.println(MessageFormat.format(" - \"{0}\"", childNode.getText().trim()));
} else {
System.out.println();
}
}
}
getNodeType in class NodeNodeType.CELL. The returned value is one of NodeType constants.public Cell getNextCell()
Cell node.
Remarks:
The method can be used when you need to have typed access to cells of a Row. If a StructuredDocumentTag node is found in a row instead of a cell, it is automatically traversed to get a cell contained within.
Examples:
Shows how to enumerate through all table cells.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = doc.getFirstSection().getBody().getTables().get(0);
// Enumerate through all cells of the table.
for (Row row = table.getFirstRow(); row != null; row = row.getNextRow())
{
for (Cell cell = row.getFirstCell(); cell != null; cell = cell.getNextCell())
{
System.out.println(cell.getText());
}
}
Cell node.public Cell getPreviousCell()
Cell node.
Remarks:
The method can be used when you need to have typed access to cells of a Row. If a StructuredDocumentTag node is found in a row instead of a cell, it is automatically traversed to get a cell contained within.
Examples:
Shows how to enumerate through all table cells.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = doc.getFirstSection().getBody().getTables().get(0);
// Enumerate through all cells of the table.
for (Row row = table.getFirstRow(); row != null; row = row.getNextRow())
{
for (Cell cell = row.getFirstCell(); cell != null; cell = cell.getNextCell())
{
System.out.println(cell.getText());
}
}
Cell node.public Row getParentRow()
Examples:
Shows how to set a table to stay together on the same page.
Document doc = new Document(getMyDir() + "Table spanning two pages.docx");
Table table = doc.getFirstSection().getBody().getTables().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 (Cell cell : (Iterable<Cell>) table.getChildNodes(NodeType.CELL, true))
for (Paragraph para : cell.getParagraphs()) {
Assert.assertTrue(para.isInCell());
if (!(cell.getParentRow().isLastRow() && para.isEndOfCell()))
para.getParagraphFormat().setKeepWithNext(true);
}
doc.save(getArtifactsDir() + "Table.KeepTableTogether.docx");
public Paragraph getFirstParagraph()
Examples:
Shows how to create a nested table using a document builder.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Build the outer table.
Cell cell = builder.insertCell();
builder.writeln("Outer Table Cell 1");
builder.insertCell();
builder.writeln("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.getFirstParagraph());
builder.insertCell();
builder.writeln("Inner Table Cell 1");
builder.insertCell();
builder.writeln("Inner Table Cell 2");
builder.endTable();
doc.save(getArtifactsDir() + "DocumentBuilder.InsertNestedTable.docx");
Shows how to build a nested table without using a document builder.
public void createNestedTable() throws Exception {
Document doc = new Document();
// Create the outer table with three rows and four columns, and then add it to the document.
Table outerTable = createTable(doc, 3, 4, "Outer Table");
doc.getFirstSection().getBody().appendChild(outerTable);
// Create another table with two rows and two columns and then insert it into the first table's first cell.
Table innerTable = createTable(doc, 2, 2, "Inner Table");
outerTable.getFirstRow().getFirstCell().appendChild(innerTable);
doc.save(getArtifactsDir() + "Table.CreateNestedTable.docx");
}
// Creates a new table in the document with the given dimensions and text in each cell.
private Table createTable(final Document doc, final int rowCount, final int cellCount, final String cellText) throws Exception {
Table table = new Table(doc);
for (int rowId = 1; rowId <= rowCount; rowId++) {
Row row = new Row(doc);
table.appendChild(row);
for (int cellId = 1; cellId <= cellCount; cellId++) {
Cell cell = new Cell(doc);
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().appendChild(new 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.setTitle("Aspose table title");
table.setDescription("Aspose table description");
return table;
}
public Paragraph getLastParagraph()
Examples:
Shows how to apply settings to vertical borders to a table row's format.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a table with red and blue inner borders.
Table table = builder.startTable();
for (int i = 0; i < 3; i++) {
builder.insertCell();
builder.write(MessageFormat.format("Row {0}, Column 1", i + 1));
builder.insertCell();
builder.write(MessageFormat.format("Row {0}, Column 2", i + 1));
Row row = builder.endRow();
BorderCollection borders = row.getRowFormat().getBorders();
// Adjust the appearance of borders that will appear between rows.
borders.getHorizontal().setColor(Color.RED);
borders.getHorizontal().setLineStyle(LineStyle.DOT);
borders.getHorizontal().setLineWidth(2.0d);
// Adjust the appearance of borders that will appear between cells.
borders.getVertical().setColor(Color.BLUE);
borders.getVertical().setLineStyle(LineStyle.DOT);
borders.getVertical().setLineWidth(2.0d);
}
// A row format, and a cell's inner paragraph use different border settings.
Border border = table.getFirstRow().getFirstCell().getLastParagraph().getParagraphFormat().getBorders().getVertical();
Assert.assertEquals(0, border.getColor().getRGB());
Assert.assertEquals(0.0d, border.getLineWidth());
Assert.assertEquals(LineStyle.NONE, border.getLineStyle());
doc.save(getArtifactsDir() + "Border.VerticalBorders.docx");
public boolean isFirstCell()
Examples:
Shows how to print the node structure of every table in a document.
public void tableToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new 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);
System.out.println(visitor.getText());
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered Table nodes and their children.
/// </summary>
public static class TableStructurePrinter extends DocumentVisitor {
public TableStructurePrinter() {
mVisitedTables = new StringBuilder();
mVisitorIsInsideTable = false;
}
public String getText() {
return mVisitedTables.toString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// Runs that are not within tables are not recorded.
/// </summary>
public int visitRun(Run run) {
if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Table is encountered in the document.
/// </summary>
public int visitTableStart(final Table table) {
int rows = 0;
int columns = 0;
if (table.getRows().getCount() > 0) {
rows = table.getRows().getCount();
columns = table.getFirstRow().getCount();
}
indentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Table node have been visited.
/// </summary>
public int visitTableEnd(final Table table) {
mDocTraversalDepth--;
indentAndAppendLine("[Table end]");
mVisitorIsInsideTable = false;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Row node is encountered in the document.
/// </summary>
public int visitRowStart(final Row row) {
String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", "");
int rowWidth = row.indexOf(row.getLastCell()) + 1;
int rowIndex = row.getParentTable().indexOf(row);
String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : "";
if (!"".equals(rowStatusInTable)) {
rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable);
}
indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Row node have been visited.
/// </summary>
public int visitRowEnd(final Row row) {
mDocTraversalDepth--;
indentAndAppendLine("[Row end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Cell node is encountered in the document.
/// </summary>
public int visitCellStart(final Cell cell) {
Row row = cell.getParentRow();
Table table = row.getParentTable();
String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : "";
if (!"".equals(cellStatusInRow)) {
cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow);
}
indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Cell node have been visited.
/// </summary>
public int visitCellEnd(final Cell cell) {
mDocTraversalDepth--;
indentAndAppendLine("[Cell end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Append a line to the StringBuilder, and indent it depending on how deep the visitor is
/// into the current table's tree of child nodes.
/// </summary>
/// <param name="text"></param>
private void indentAndAppendLine(final String text) {
for (int i = 0; i < mDocTraversalDepth; i++) {
mVisitedTables.append("| ");
}
mVisitedTables.append(text + "\r\n");
}
private boolean mVisitorIsInsideTable;
private int mDocTraversalDepth;
private final StringBuilder mVisitedTables;
}
boolean value.public boolean isLastCell()
Examples:
Shows how to print the node structure of every table in a document.
public void tableToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new 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);
System.out.println(visitor.getText());
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered Table nodes and their children.
/// </summary>
public static class TableStructurePrinter extends DocumentVisitor {
public TableStructurePrinter() {
mVisitedTables = new StringBuilder();
mVisitorIsInsideTable = false;
}
public String getText() {
return mVisitedTables.toString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// Runs that are not within tables are not recorded.
/// </summary>
public int visitRun(Run run) {
if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Table is encountered in the document.
/// </summary>
public int visitTableStart(final Table table) {
int rows = 0;
int columns = 0;
if (table.getRows().getCount() > 0) {
rows = table.getRows().getCount();
columns = table.getFirstRow().getCount();
}
indentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Table node have been visited.
/// </summary>
public int visitTableEnd(final Table table) {
mDocTraversalDepth--;
indentAndAppendLine("[Table end]");
mVisitorIsInsideTable = false;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Row node is encountered in the document.
/// </summary>
public int visitRowStart(final Row row) {
String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", "");
int rowWidth = row.indexOf(row.getLastCell()) + 1;
int rowIndex = row.getParentTable().indexOf(row);
String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : "";
if (!"".equals(rowStatusInTable)) {
rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable);
}
indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Row node have been visited.
/// </summary>
public int visitRowEnd(final Row row) {
mDocTraversalDepth--;
indentAndAppendLine("[Row end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Cell node is encountered in the document.
/// </summary>
public int visitCellStart(final Cell cell) {
Row row = cell.getParentRow();
Table table = row.getParentTable();
String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : "";
if (!"".equals(cellStatusInRow)) {
cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow);
}
indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Cell node have been visited.
/// </summary>
public int visitCellEnd(final Cell cell) {
mDocTraversalDepth--;
indentAndAppendLine("[Cell end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Append a line to the StringBuilder, and indent it depending on how deep the visitor is
/// into the current table's tree of child nodes.
/// </summary>
/// <param name="text"></param>
private void indentAndAppendLine(final String text) {
for (int i = 0; i < mDocTraversalDepth; i++) {
mVisitedTables.append("| ");
}
mVisitedTables.append(text + "\r\n");
}
private boolean mVisitorIsInsideTable;
private int mDocTraversalDepth;
private final StringBuilder mVisitedTables;
}
boolean value.public CellFormat getCellFormat()
Examples:
Shows how to modify formatting of a table cell.
Document doc = new Document(getMyDir() + "Tables.docx");
Table table = doc.getFirstSection().getBody().getTables().get(0);
Cell firstCell = table.getFirstRow().getFirstCell();
// Use a cell's "CellFormat" property to set formatting that modifies the appearance of that cell.
firstCell.getCellFormat().setWidth(30.0);
firstCell.getCellFormat().setOrientation(TextOrientation.DOWNWARD);
firstCell.getCellFormat().getShading().setForegroundPatternColor(Color.GREEN);
doc.save(getArtifactsDir() + "Table.CellFormat.docx");
Shows how to combine the rows from two tables into one.
Document doc = new Document(getMyDir() + "Tables.docx");
// Below are two ways of getting a table from a document.
// 1 - From the "Tables" collection of a Body node:
Table firstTable = doc.getFirstSection().getBody().getTables().get(0);
// 2 - Using the "GetChild" method:
Table secondTable = (Table) doc.getChild(NodeType.TABLE, 1, true);
// Append all rows from the current table to the next.
while (secondTable.hasChildNodes())
firstTable.getRows().add(secondTable.getFirstRow());
// Remove the empty table container.
secondTable.remove();
doc.save(getArtifactsDir() + "Table.CombineTables.docx");
Shows how to modify the format of rows and cells in a table.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.startTable();
builder.insertCell();
builder.write("City");
builder.insertCell();
builder.write("Country");
builder.endRow();
builder.insertCell();
builder.write("London");
builder.insertCell();
builder.write("U.K.");
builder.endTable();
// Use the first row's "RowFormat" property to modify the formatting
// of the contents of all cells in this row.
RowFormat rowFormat = table.getFirstRow().getRowFormat();
rowFormat.setHeight(25.0);
rowFormat.getBorders().getByBorderType(BorderType.BOTTOM).setColor(Color.RED);
// Use the "CellFormat" property of the first cell in the last row to modify the formatting of that cell's contents.
CellFormat cellFormat = table.getLastRow().getFirstCell().getCellFormat();
cellFormat.setWidth(100.0);
cellFormat.getShading().setBackgroundPatternColor(Color.ORANGE);
doc.save(getArtifactsDir() + "Table.RowCellFormat.docx");
CellFormat value.public ParagraphCollection getParagraphs()
Examples:
Shows how to set a table to stay together on the same page.
Document doc = new Document(getMyDir() + "Table spanning two pages.docx");
Table table = doc.getFirstSection().getBody().getTables().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 (Cell cell : (Iterable<Cell>) table.getChildNodes(NodeType.CELL, true))
for (Paragraph para : cell.getParagraphs()) {
Assert.assertTrue(para.isInCell());
if (!(cell.getParentRow().isLastRow() && para.isEndOfCell()))
para.getParagraphFormat().setKeepWithNext(true);
}
doc.save(getArtifactsDir() + "Table.KeepTableTogether.docx");
public TableCollection getTables()
Examples:
Shows how to find out if a tables are nested.
public void calculateDepthOfNestedTables() throws Exception {
Document doc = new Document(getMyDir() + "Nested tables.docx");
NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);
for (int i = 0; i < tables.getCount(); i++) {
Table table = (Table) tables.get(i);
// Find out if any cells in the table have other tables as children.
int count = getChildTableCount(table);
System.out.print(MessageFormat.format("Table #{0} has {1} tables directly within its cells", i, count));
// Find out if the table is nested inside another table, and, if so, at what depth.
int tableDepth = getNestedDepthOfTable(table);
if (tableDepth > 0)
System.out.println(MessageFormat.format("Table #{0} is nested inside another table at depth of {1}", i, tableDepth));
else
System.out.println(MessageFormat.format("Table #{0} is a non nested table (is not a child of another table)", i));
}
}
// Calculates what level a table is nested inside other tables.
//
// Returns An integer containing the level the table is nested at.
// 0 = Table is not nested inside any other table
// 1 = Table is nested within one parent table
// 2 = Table is nested within two parent tables etc..
private static int getNestedDepthOfTable(final Table table) {
int depth = 0;
Node parent = table.getAncestor(table.getNodeType());
while (parent != null) {
depth++;
parent = parent.getAncestor(Table.class);
}
return depth;
}
// Determines if a table contains any immediate child table within its cells.
// Does not recursively traverse through those tables to check for further tables.
//
// Returns true if at least one child cell contains a table.
// Returns false if no cells in the table contains a table.
private static int getChildTableCount(final Table table) {
int childTableCount = 0;
for (Row row : table.getRows()) {
for (Cell cell : row.getCells()) {
TableCollection childTables = cell.getTables();
if (childTables.getCount() > 0) childTableCount++;
}
}
return childTableCount;
}
public boolean accept(DocumentVisitor visitor) throws java.lang.Exception
Remarks:
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.
Calls DocumentVisitor.visitCellStart(com.aspose.words.Cell), then calls Node.accept(com.aspose.words.DocumentVisitor) for all child nodes of the section and calls DocumentVisitor.visitCellEnd(com.aspose.words.Cell) at the end.
Examples:
Shows how to print the node structure of every table in a document.
public void tableToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new 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);
System.out.println(visitor.getText());
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered Table nodes and their children.
/// </summary>
public static class TableStructurePrinter extends DocumentVisitor {
public TableStructurePrinter() {
mVisitedTables = new StringBuilder();
mVisitorIsInsideTable = false;
}
public String getText() {
return mVisitedTables.toString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// Runs that are not within tables are not recorded.
/// </summary>
public int visitRun(Run run) {
if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Table is encountered in the document.
/// </summary>
public int visitTableStart(final Table table) {
int rows = 0;
int columns = 0;
if (table.getRows().getCount() > 0) {
rows = table.getRows().getCount();
columns = table.getFirstRow().getCount();
}
indentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Table node have been visited.
/// </summary>
public int visitTableEnd(final Table table) {
mDocTraversalDepth--;
indentAndAppendLine("[Table end]");
mVisitorIsInsideTable = false;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Row node is encountered in the document.
/// </summary>
public int visitRowStart(final Row row) {
String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", "");
int rowWidth = row.indexOf(row.getLastCell()) + 1;
int rowIndex = row.getParentTable().indexOf(row);
String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : "";
if (!"".equals(rowStatusInTable)) {
rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable);
}
indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Row node have been visited.
/// </summary>
public int visitRowEnd(final Row row) {
mDocTraversalDepth--;
indentAndAppendLine("[Row end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Cell node is encountered in the document.
/// </summary>
public int visitCellStart(final Cell cell) {
Row row = cell.getParentRow();
Table table = row.getParentTable();
String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : "";
if (!"".equals(cellStatusInRow)) {
cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow);
}
indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Cell node have been visited.
/// </summary>
public int visitCellEnd(final Cell cell) {
mDocTraversalDepth--;
indentAndAppendLine("[Cell end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Append a line to the StringBuilder, and indent it depending on how deep the visitor is
/// into the current table's tree of child nodes.
/// </summary>
/// <param name="text"></param>
private void indentAndAppendLine(final String text) {
for (int i = 0; i < mDocTraversalDepth; i++) {
mVisitedTables.append("| ");
}
mVisitedTables.append(text + "\r\n");
}
private boolean mVisitorIsInsideTable;
private int mDocTraversalDepth;
private final StringBuilder mVisitedTables;
}
accept in class Nodevisitor - The visitor that will visit the nodes.DocumentVisitor stopped the operation before visiting all nodes.java.lang.Exceptionpublic int acceptStart(DocumentVisitor visitor) throws java.lang.Exception
Examples:
Shows how to print the node structure of every table in a document.
public void tableToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new 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);
System.out.println(visitor.getText());
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered Table nodes and their children.
/// </summary>
public static class TableStructurePrinter extends DocumentVisitor {
public TableStructurePrinter() {
mVisitedTables = new StringBuilder();
mVisitorIsInsideTable = false;
}
public String getText() {
return mVisitedTables.toString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// Runs that are not within tables are not recorded.
/// </summary>
public int visitRun(Run run) {
if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Table is encountered in the document.
/// </summary>
public int visitTableStart(final Table table) {
int rows = 0;
int columns = 0;
if (table.getRows().getCount() > 0) {
rows = table.getRows().getCount();
columns = table.getFirstRow().getCount();
}
indentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Table node have been visited.
/// </summary>
public int visitTableEnd(final Table table) {
mDocTraversalDepth--;
indentAndAppendLine("[Table end]");
mVisitorIsInsideTable = false;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Row node is encountered in the document.
/// </summary>
public int visitRowStart(final Row row) {
String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", "");
int rowWidth = row.indexOf(row.getLastCell()) + 1;
int rowIndex = row.getParentTable().indexOf(row);
String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : "";
if (!"".equals(rowStatusInTable)) {
rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable);
}
indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Row node have been visited.
/// </summary>
public int visitRowEnd(final Row row) {
mDocTraversalDepth--;
indentAndAppendLine("[Row end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Cell node is encountered in the document.
/// </summary>
public int visitCellStart(final Cell cell) {
Row row = cell.getParentRow();
Table table = row.getParentTable();
String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : "";
if (!"".equals(cellStatusInRow)) {
cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow);
}
indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Cell node have been visited.
/// </summary>
public int visitCellEnd(final Cell cell) {
mDocTraversalDepth--;
indentAndAppendLine("[Cell end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Append a line to the StringBuilder, and indent it depending on how deep the visitor is
/// into the current table's tree of child nodes.
/// </summary>
/// <param name="text"></param>
private void indentAndAppendLine(final String text) {
for (int i = 0; i < mDocTraversalDepth; i++) {
mVisitedTables.append("| ");
}
mVisitedTables.append(text + "\r\n");
}
private boolean mVisitorIsInsideTable;
private int mDocTraversalDepth;
private final StringBuilder mVisitedTables;
}
acceptStart in class CompositeNodevisitor - The document visitor.VisitorAction constants.java.lang.Exceptionpublic int acceptEnd(DocumentVisitor visitor) throws java.lang.Exception
Examples:
Shows how to print the node structure of every table in a document.
public void tableToText() throws Exception {
Document doc = new Document(getMyDir() + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new 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);
System.out.println(visitor.getText());
}
/// <summary>
/// Traverses a node's non-binary tree of child nodes.
/// Creates a map in the form of a string of all encountered Table nodes and their children.
/// </summary>
public static class TableStructurePrinter extends DocumentVisitor {
public TableStructurePrinter() {
mVisitedTables = new StringBuilder();
mVisitorIsInsideTable = false;
}
public String getText() {
return mVisitedTables.toString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// Runs that are not within tables are not recorded.
/// </summary>
public int visitRun(Run run) {
if (mVisitorIsInsideTable) indentAndAppendLine("[Run] \"" + run.getText() + "\"");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Table is encountered in the document.
/// </summary>
public int visitTableStart(final Table table) {
int rows = 0;
int columns = 0;
if (table.getRows().getCount() > 0) {
rows = table.getRows().getCount();
columns = table.getFirstRow().getCount();
}
indentAndAppendLine("[Table start] Size: " + rows + "x" + columns);
mDocTraversalDepth++;
mVisitorIsInsideTable = true;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Table node have been visited.
/// </summary>
public int visitTableEnd(final Table table) {
mDocTraversalDepth--;
indentAndAppendLine("[Table end]");
mVisitorIsInsideTable = false;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Row node is encountered in the document.
/// </summary>
public int visitRowStart(final Row row) {
String rowContents = row.getText().replaceAll("\\u0007", ", ").replaceAll(", , ", "");
int rowWidth = row.indexOf(row.getLastCell()) + 1;
int rowIndex = row.getParentTable().indexOf(row);
String rowStatusInTable = row.isFirstRow() && row.isLastRow() ? "only" : row.isFirstRow() ? "first" : row.isLastRow() ? "last" : "";
if (!"".equals(rowStatusInTable)) {
rowStatusInTable = MessageFormat.format(", the {0} row in this table,", rowStatusInTable);
}
indentAndAppendLine(MessageFormat.format("[Row start] Row #{0}{1} width {2}, \"{3}\"", ++rowIndex, rowStatusInTable, rowWidth, rowContents));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Row node have been visited.
/// </summary>
public int visitRowEnd(final Row row) {
mDocTraversalDepth--;
indentAndAppendLine("[Row end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called when a Cell node is encountered in the document.
/// </summary>
public int visitCellStart(final Cell cell) {
Row row = cell.getParentRow();
Table table = row.getParentTable();
String cellStatusInRow = cell.isFirstCell() && cell.isLastCell() ? "only" : cell.isFirstCell() ? "first" : cell.isLastCell() ? "last" : "";
if (!"".equals(cellStatusInRow)) {
cellStatusInRow = MessageFormat.format(", the {0} cell in this row", cellStatusInRow);
}
indentAndAppendLine(MessageFormat.format("[Cell start] Row {0}, Col {1}{2}", table.indexOf(row) + 1, row.indexOf(cell) + 1, cellStatusInRow));
mDocTraversalDepth++;
return VisitorAction.CONTINUE;
}
/// <summary>
/// Called after all the child nodes of a Cell node have been visited.
/// </summary>
public int visitCellEnd(final Cell cell) {
mDocTraversalDepth--;
indentAndAppendLine("[Cell end]");
return VisitorAction.CONTINUE;
}
/// <summary>
/// Append a line to the StringBuilder, and indent it depending on how deep the visitor is
/// into the current table's tree of child nodes.
/// </summary>
/// <param name="text"></param>
private void indentAndAppendLine(final String text) {
for (int i = 0; i < mDocTraversalDepth; i++) {
mVisitedTables.append("| ");
}
mVisitedTables.append(text + "\r\n");
}
private boolean mVisitorIsInsideTable;
private int mDocTraversalDepth;
private final StringBuilder mVisitedTables;
}
acceptEnd in class CompositeNodevisitor - The document visitor.VisitorAction constants.java.lang.Exceptionpublic void ensureMinimum()
Examples:
Shows how to ensure a cell node contains the nodes we need to begin adding content to it.
Document doc = new Document();
Table table = new Table(doc);
doc.getFirstSection().getBody().appendChild(table);
Row row = new Row(doc);
table.appendChild(row);
Cell cell = new 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.assertEquals(0, cell.getChildNodes(NodeType.ANY, true).getCount());
// 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.getFirstParagraph().appendChild(new Run(doc, "Hello world!"));
public java.lang.Object getDirectCellAttr(int key)
public java.lang.Object fetchCellAttr(int key)
public java.lang.Object fetchInheritedCellAttr(int key)
public void setCellAttr(int key,
java.lang.Object value)
public void clearCellAttrs()
public void removeMoveRevisions()