com.aspose.words

Class CellFormat

  • java.lang.Object
    • com.aspose.words.CellFormat
public class CellFormat 
extends java.lang.Object

Represents all formatting for a table cell.

Example:

Shows how to modify formatting of a table cell.
Document doc = new Document(getMyDir() + "Table.Document.doc");
Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);

// Retrieve the first cell in the table.
Cell firstCell = table.getFirstRow().getFirstCell();

// Modify some row level properties.
firstCell.getCellFormat().setWidth(30); // in points
firstCell.getCellFormat().setOrientation(TextOrientation.DOWNWARD);
firstCell.getCellFormat().getShading().setForegroundPatternColor(Color.GREEN);

Example:

Shows how to insert a table using the constructors of nodes.
Document doc = new Document();

// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.getFirstSection().getBody().appendChild(table);

// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.

// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorthim for example.
Row row = new Row(doc);
row.getRowFormat().setAllowBreakAcrossPages(true);
table.appendChild(row);

// We can now apply any auto fit settings.
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
cell.getCellFormat().setWidth(80);

// Add a paragraph to the cell as well as a new run with some text.
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 1 Text"));

// Add the cell to the row.
row.appendChild(cell);

// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.appendChild(cell.deepClone(false));
row.getLastCell().appendChild(new Paragraph(doc));
row.getLastCell().getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 2 Text"));

doc.save(getMyDir() + "\\Artifacts\\Table.InsertTableUsingNodes.doc");

Property Getters/Setters Summary
BorderCollectiongetBorders()
Gets collection of borders of the cell.
doublegetBottomPadding()
void
setBottomPadding(doublevalue)
           Returns or sets the amount of space (in points) to add below the contents of cell.
booleangetFitText()
void
setFitText(booleanvalue)
           If true, fits text in the cell, compressing each paragraph to the width of the cell.
intgetHorizontalMerge()
void
           Specifies how the cell is merged horizontally with other cells in the row. The value of the property is CellMerge integer constant.
doublegetLeftPadding()
void
setLeftPadding(doublevalue)
           Returns or sets the amount of space (in points) to add to the left of the contents of cell.
intgetOrientation()
void
setOrientation(intvalue)
           Returns or sets the orientation of text in a table cell. The value of the property is TextOrientation integer constant.
PreferredWidthgetPreferredWidth()
void
           Returns or sets the preferred width of the cell.
doublegetRightPadding()
void
setRightPadding(doublevalue)
           Returns or sets the amount of space (in points) to add to the right of the contents of cell.
ShadinggetShading()
Returns a Shading object that refers to the shading formatting for the cell.
doublegetTopPadding()
void
setTopPadding(doublevalue)
           Returns or sets the amount of space (in points) to add above the contents of cell.
intgetVerticalAlignment()
void
           Returns or sets the vertical alignment of text in the cell. The value of the property is CellVerticalAlignment integer constant.
intgetVerticalMerge()
void
           Specifies how the cell is merged with other cells vertically. The value of the property is CellMerge integer constant.
doublegetWidth()
void
setWidth(doublevalue)
           Gets the width of the cell in points.
booleangetWrapText()
void
setWrapText(booleanvalue)
           If true, wrap text for the cell.
 
Method Summary
voidclearFormatting()
Resets to default cell formatting. Does not change the width of the cell.
voidsetPaddings(double leftPadding, double topPadding, double rightPadding, double bottomPadding)
Sets the amount of space (in points) to add to the left/top/right/bottom of the contents of cell.
 

    • Property Getters/Setters Detail

      • getBorders

        public BorderCollection getBorders()
        
        Gets collection of borders of the cell.

        Example:

        Shows how to combine the rows from two tables into one.
        // Load the document.
        Document doc = new Document(getMyDir() + "Table.Document.doc");
        
        // Get the first and second table in the document.
        // The rows from the second table will be appended to the end of the first table.
        Table firstTable = (Table) doc.getChild(NodeType.TABLE, 0, true);
        Table secondTable = (Table) doc.getChild(NodeType.TABLE, 1, true);
        
        // Append all rows from the current table to the next.
        // Due to the design of tables even tables with different cell count and widths can be joined into one table.
        while (secondTable.hasChildNodes()) firstTable.getRows().add(secondTable.getFirstRow());
        
        // Remove the empty table container.
        secondTable.remove();
        
        doc.save(getMyDir() + "\\Artifacts\\Table.CombineTables.doc");
      • getBottomPadding/setBottomPadding

        public double getBottomPadding() / public void setBottomPadding(double value)
        
        Returns or sets the amount of space (in points) to add below the contents of cell.

        Example:

        Shows how to create a table that contains a single formatted cell.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.startTable();
        builder.insertCell();
        
        // Set the cell formatting
        CellFormat cellFormat = builder.getCellFormat();
        cellFormat.setWidth(250);
        cellFormat.setLeftPadding(30);
        cellFormat.setRightPadding(30);
        cellFormat.setTopPadding(30);
        cellFormat.setBottomPadding(30);
        
        builder.writeln("I'm a wonderful formatted cell.");
        
        builder.endRow();
        builder.endTable();
      • getFitText/setFitText

        public boolean getFitText() / public void setFitText(boolean value)
        
        If true, fits text in the cell, compressing each paragraph to the width of the cell.
      • getHorizontalMerge/setHorizontalMerge

        public int getHorizontalMerge() / public void setHorizontalMerge(int value)
        
        Specifies how the cell is merged horizontally with other cells in the row. The value of the property is CellMerge integer constant.

        Example:

        Creates a table with two rows with cells in the first row horizontally merged.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
        builder.write("Text in merged cells.");
        
        builder.insertCell();
        // This cell is merged to the previous and should be empty.
        builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
        builder.endRow();
        
        builder.insertCell();
        builder.getCellFormat().setHorizontalMerge(CellMerge.NONE);
        builder.write("Text in one cell.");
        
        builder.insertCell();
        builder.write("Text in another cell.");
        builder.endRow();
        builder.endTable();

        Example:

        Prints the horizontal and vertical merge type of a cell.
        public void checkCellsMerged() throws Exception
        {
            Document doc = new Document(getMyDir() + "Table.MergedCells.doc");
        
            // Retrieve the first table in the document.
            Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        
            for (Row row : table.getRows())
            {
                for (Cell cell : row.getCells())
                {
                    System.out.println(printCellMergeType(cell));
                }
            }
        
        }
        
        public String printCellMergeType(Cell cell)
        {
            boolean isHorizontallyMerged = cell.getCellFormat().getHorizontalMerge() != CellMerge.NONE;
            boolean isVerticallyMerged = cell.getCellFormat().getVerticalMerge() != CellMerge.NONE;
            String cellLocation = MessageFormat.format("R{0}, C{1}", cell.getParentRow().getParentTable().indexOf(cell.getParentRow()) + 1, cell.getParentRow().indexOf(cell) + 1);
        
            if (isHorizontallyMerged && isVerticallyMerged)
                return MessageFormat.format("The cell at {0} is both horizontally and vertically merged", cellLocation);
            else if (isHorizontallyMerged)
                return MessageFormat.format("The cell at {0} is horizontally merged.", cellLocation);
            else if (isVerticallyMerged) return MessageFormat.format("The cell at {0} is vertically merged", cellLocation);
            else return MessageFormat.format("The cell at {0} is not merged", cellLocation);
        }
        See Also:
        VerticalMerge
      • getLeftPadding/setLeftPadding

        public double getLeftPadding() / public void setLeftPadding(double value)
        
        Returns or sets the amount of space (in points) to add to the left of the contents of cell.

        Example:

        Shows how to create a table that contains a single formatted cell.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.startTable();
        builder.insertCell();
        
        // Set the cell formatting
        CellFormat cellFormat = builder.getCellFormat();
        cellFormat.setWidth(250);
        cellFormat.setLeftPadding(30);
        cellFormat.setRightPadding(30);
        cellFormat.setTopPadding(30);
        cellFormat.setBottomPadding(30);
        
        builder.writeln("I'm a wonderful formatted cell.");
        
        builder.endRow();
        builder.endTable();
      • getOrientation/setOrientation

        public int getOrientation() / public void setOrientation(int value)
        
        Returns or sets the orientation of text in a table cell. The value of the property is TextOrientation integer constant.

        Example:

        Shows how to build a formatted table that contains 2 rows and 2 columns.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        Table table = builder.startTable();
        
        // Insert a cell
        builder.insertCell();
        // Use fixed column widths.
        table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
        
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        builder.write("This is row 1 cell 1");
        
        // Insert a cell
        builder.insertCell();
        builder.write("This is row 1 cell 2");
        
        builder.endRow();
        
        // Insert a cell
        builder.insertCell();
        
        // Apply new row formatting
        builder.getRowFormat().setHeight(100);
        builder.getRowFormat().setHeightRule(HeightRule.EXACTLY);
        
        builder.getCellFormat().setOrientation(TextOrientation.UPWARD);
        builder.writeln("This is row 2 cell 1");
        
        // Insert a cell
        builder.insertCell();
        builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD);
        builder.writeln("This is row 2 cell 2");
        
        builder.endRow();
        
        builder.endTable();
      • getPreferredWidth/setPreferredWidth

        public PreferredWidth getPreferredWidth() / public void setPreferredWidth(PreferredWidth value)
        
        Returns or sets the preferred width of the cell.

        The preferred width (along with the table's Auto Fit option) determines how the actual width of the cell is calculated by the table layout algorithm. Table layout can be performed by Aspose.Words when it saves the document or by Microsoft Word when it displays the document.

        The preferred width can be specified in points or in percent. The preferred width can also be specified as "auto", which means no preferred width is specified.

        The default value is PreferredWidth.AUTO.

        Example:

        Shows how to set the different preferred width settings.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Insert a table row made up of three cells which have different preferred widths.
        Table table = builder.startTable();
        
        // Insert an absolute sized cell.
        builder.insertCell();
        builder.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(40));
        builder.getCellFormat().getShading().setBackgroundPatternColor(Color.RED);
        builder.writeln("Cell at 40 points width");
        
        // Insert a relative (percent) sized cell.
        builder.insertCell();
        builder.getCellFormat().setPreferredWidth(PreferredWidth.fromPercent(20));
        builder.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
        builder.writeln("Cell at 20% width");
        
        // Insert a auto sized cell.
        builder.insertCell();
        builder.getCellFormat().setPreferredWidth(PreferredWidth.AUTO);
        builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN);
        builder.writeln("Cell automatically sized. The size of this cell is calculated from the table preferred width.");
        builder.writeln("In this case the cell will fill up the rest of the available space.");
        
        doc.save(getMyDir() + "\\Artifacts\\Table.CellPreferredWidths.doc");
        See Also:
        Width
      • getRightPadding/setRightPadding

        public double getRightPadding() / public void setRightPadding(double value)
        
        Returns or sets the amount of space (in points) to add to the right of the contents of cell.

        Example:

        Shows how to create a table that contains a single formatted cell.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.startTable();
        builder.insertCell();
        
        // Set the cell formatting
        CellFormat cellFormat = builder.getCellFormat();
        cellFormat.setWidth(250);
        cellFormat.setLeftPadding(30);
        cellFormat.setRightPadding(30);
        cellFormat.setTopPadding(30);
        cellFormat.setBottomPadding(30);
        
        builder.writeln("I'm a wonderful formatted cell.");
        
        builder.endRow();
        builder.endTable();
      • getShading

        public Shading getShading()
        
        Returns a Shading object that refers to the shading formatting for the cell.

        Example:

        Shows how to insert a table using the constructors of nodes.
        Document doc = new Document();
        
        // We start by creating the table object. Note how we must pass the document object
        // to the constructor of each node. This is because every node we create must belong
        // to some document.
        Table table = new Table(doc);
        // Add the table to the document.
        doc.getFirstSection().getBody().appendChild(table);
        
        // Here we could call EnsureMinimum to create the rows and cells for us. This method is used
        // to ensure that the specified node is valid, in this case a valid table should have at least one
        // row and one cell, therefore this method creates them for us.
        
        // Instead we will handle creating the row and table ourselves. This would be the best way to do this
        // if we were creating a table inside an algorthim for example.
        Row row = new Row(doc);
        row.getRowFormat().setAllowBreakAcrossPages(true);
        table.appendChild(row);
        
        // We can now apply any auto fit settings.
        table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
        
        // Create a cell and add it to the row
        Cell cell = new Cell(doc);
        cell.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
        cell.getCellFormat().setWidth(80);
        
        // Add a paragraph to the cell as well as a new run with some text.
        cell.appendChild(new Paragraph(doc));
        cell.getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 1 Text"));
        
        // Add the cell to the row.
        row.appendChild(cell);
        
        // We would then repeat the process for the other cells and rows in the table.
        // We can also speed things up by cloning existing cells and rows.
        row.appendChild(cell.deepClone(false));
        row.getLastCell().appendChild(new Paragraph(doc));
        row.getLastCell().getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 2 Text"));
        
        doc.save(getMyDir() + "\\Artifacts\\Table.InsertTableUsingNodes.doc");
      • getTopPadding/setTopPadding

        public double getTopPadding() / public void setTopPadding(double value)
        
        Returns or sets the amount of space (in points) to add above the contents of cell.

        Example:

        Shows how to create a table that contains a single formatted cell.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.startTable();
        builder.insertCell();
        
        // Set the cell formatting
        CellFormat cellFormat = builder.getCellFormat();
        cellFormat.setWidth(250);
        cellFormat.setLeftPadding(30);
        cellFormat.setRightPadding(30);
        cellFormat.setTopPadding(30);
        cellFormat.setBottomPadding(30);
        
        builder.writeln("I'm a wonderful formatted cell.");
        
        builder.endRow();
        builder.endTable();
      • getVerticalAlignment/setVerticalAlignment

        public int getVerticalAlignment() / public void setVerticalAlignment(int value)
        
        Returns or sets the vertical alignment of text in the cell. The value of the property is CellVerticalAlignment integer constant.
      • getVerticalMerge/setVerticalMerge

        public int getVerticalMerge() / public void setVerticalMerge(int value)
        
        Specifies how the cell is merged with other cells vertically. The value of the property is CellMerge integer constant.

        Cells can only be merged vertically if their left and right boundaries are identical.

        When cells are vertically merged, the display areas of the merged cells are consolidated. The consolidated area is used to display the contents of the first vertically merged cell and all other vertically merged cells must be empty.

        Example:

        Creates a table with two columns with cells merged vertically in the first column.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
        builder.write("Text in merged cells.");
        
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.write("Text in one cell");
        builder.endRow();
        
        builder.insertCell();
        // This cell is vertically merged to the cell above and should be empty.
        builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
        
        builder.insertCell();
        builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
        builder.write("Text in another cell");
        builder.endRow();
        builder.endTable();

        Example:

        Prints the horizontal and vertical merge type of a cell.
        public void checkCellsMerged() throws Exception
        {
            Document doc = new Document(getMyDir() + "Table.MergedCells.doc");
        
            // Retrieve the first table in the document.
            Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        
            for (Row row : table.getRows())
            {
                for (Cell cell : row.getCells())
                {
                    System.out.println(printCellMergeType(cell));
                }
            }
        
        }
        
        public String printCellMergeType(Cell cell)
        {
            boolean isHorizontallyMerged = cell.getCellFormat().getHorizontalMerge() != CellMerge.NONE;
            boolean isVerticallyMerged = cell.getCellFormat().getVerticalMerge() != CellMerge.NONE;
            String cellLocation = MessageFormat.format("R{0}, C{1}", cell.getParentRow().getParentTable().indexOf(cell.getParentRow()) + 1, cell.getParentRow().indexOf(cell) + 1);
        
            if (isHorizontallyMerged && isVerticallyMerged)
                return MessageFormat.format("The cell at {0} is both horizontally and vertically merged", cellLocation);
            else if (isHorizontallyMerged)
                return MessageFormat.format("The cell at {0} is horizontally merged.", cellLocation);
            else if (isVerticallyMerged) return MessageFormat.format("The cell at {0} is vertically merged", cellLocation);
            else return MessageFormat.format("The cell at {0} is not merged", cellLocation);
        }
        See Also:
        HorizontalMerge
      • getWidth/setWidth

        public double getWidth() / public void setWidth(double value)
        
        Gets the width of the cell in points.

        The width is calculated by Aspose.Words on document loading and saving. Currently, not every combination of table, cell and document properties is supported. The returned value may not be accurate for some documents. It may not exactly match the cell width as calculated by MS Word when the document is opened in MS Word.

        Setting this property is not recommended. There is no guarantee that the cell will actually have the set width. The width may be adjusted to accommodate cell contents in an auto-fit table layout. Cells in other rows may have conflicting width settings. The table may be resized to fit into the container or to meet table width settings. Consider using PreferredWidth for setting the cell width. Setting this property sets PreferredWidth implicitly since version 15.8.

        Example:

        Shows how to create a table that contains a single formatted cell.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.startTable();
        builder.insertCell();
        
        // Set the cell formatting
        CellFormat cellFormat = builder.getCellFormat();
        cellFormat.setWidth(250);
        cellFormat.setLeftPadding(30);
        cellFormat.setRightPadding(30);
        cellFormat.setTopPadding(30);
        cellFormat.setBottomPadding(30);
        
        builder.writeln("I'm a wonderful formatted cell.");
        
        builder.endRow();
        builder.endTable();
        See Also:
        PreferredWidth
      • getWrapText/setWrapText

        public boolean getWrapText() / public void setWrapText(boolean value)
        
        If true, wrap text for the cell.
    • Method Detail

      • clearFormatting

        public void clearFormatting()
        Resets to default cell formatting. Does not change the width of the cell.

        Example:

        Shows how to combine the rows from two tables into one.
        // Load the document.
        Document doc = new Document(getMyDir() + "Table.Document.doc");
        
        // Get the first and second table in the document.
        // The rows from the second table will be appended to the end of the first table.
        Table firstTable = (Table) doc.getChild(NodeType.TABLE, 0, true);
        Table secondTable = (Table) doc.getChild(NodeType.TABLE, 1, true);
        
        // Append all rows from the current table to the next.
        // Due to the design of tables even tables with different cell count and widths can be joined into one table.
        while (secondTable.hasChildNodes()) firstTable.getRows().add(secondTable.getFirstRow());
        
        // Remove the empty table container.
        secondTable.remove();
        
        doc.save(getMyDir() + "\\Artifacts\\Table.CombineTables.doc");
      • setPaddings

        public void setPaddings(double leftPadding, double topPadding, double rightPadding, double bottomPadding)
        Sets the amount of space (in points) to add to the left/top/right/bottom of the contents of cell.

        Example:

        Shows how to set paddings to a table cell.
        DocumentBuilder builder = new DocumentBuilder();
        
        builder.startTable();
        builder.getCellFormat().setWidth(300.0);
        builder.getCellFormat().setPaddings(5.0, 10.0, 40.0, 50.0);
        
        builder.getRowFormat().setHeightRule(HeightRule.EXACTLY);
        builder.getRowFormat().setHeight(50.0);
        
        builder.insertCell();
        builder.write("Row 1, Col 1");
        
        ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
        builder.getDocument().save(dstStream, SaveFormat.DOCX);
        
        Table table = (Table) builder.getDocument().getChild(NodeType.TABLE, 0, true);
        
        Cell cell = table.getRows().get(0).getCells().get(0);
        
        Assert.assertEquals(cell.getCellFormat().getLeftPadding(), 5.0);
        Assert.assertEquals(cell.getCellFormat().getTopPadding(), 10.0);
        Assert.assertEquals(cell.getCellFormat().getRightPadding(), 40.0);
        Assert.assertEquals(cell.getCellFormat().getBottomPadding(), 50.0);