Thursday, 02 July 2020 08:54

Create a Nested Table in Word in Java

Written by  support iceblue
Rate this item
(0 votes)

This article demonstrates how to insert a nested table in a table cell using Spire.Doc for Java.

import com.spire.doc.*;

public class CreateNestedTable {
    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();
        
        //Add a section
        Section section = doc.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2, 3);

        //Set column width
        table.getRows().get(0).getCells().get(0).setWidth(50f);
        table.getRows().get(0).getCells().get(2).setWidth(50f);
        table.getRows().get(1).getCells().get(0).setWidth(50f);
        table.getRows().get(1).getCells().get(2).setWidth(50f);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Insert content to cells
        table.get(0,0).addParagraph().appendText("SI.No.");
        String text = "Earthwork excavation for foundation of buildings, water supply, "
                + "sanitary lines and electrical conduits either in pits or in "
                + "trenches 1.5m and above in width, in ordinary soil not exceeding "
                + "1.5m in depth including dressing the bottom and sides of pits and  "
                + "trenches, stacking the excavated soil clear.";
        table.get(0,1).addParagraph().appendText(text);
        table.get(0,2).addParagraph().appendText("Qty");

        //Add a nested table to cell(0,1)
        Table nestedTable = table.get(0,1).addTable();
        nestedTable.resetCells(3, 4);
        nestedTable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Add content to the cells of nested table
        nestedTable.get(0,0).addParagraph().appendText("SI.No.");
        nestedTable.get(0,1).addParagraph().appendText("Item");
        nestedTable.get(0,2).addParagraph().appendText("Qty");
        nestedTable.get(0,3).addParagraph().appendText("Rate");
        nestedTable.get(1,0).addParagraph().appendText("1");
        nestedTable.get(1,1).addParagraph().appendText("Sand");
        nestedTable.get(1,2).addParagraph().appendText("30");
        nestedTable.get(1,3).addParagraph().appendText("45");
        nestedTable.get(2,0).addParagraph().appendText("2");
        nestedTable.get(2,1).addParagraph().appendText("Cement");
        nestedTable.get(2,2).addParagraph().appendText("30");
        nestedTable.get(2,3).addParagraph().appendText("50");

        //Save the document
        doc.saveToFile("NestedTable.docx", FileFormat.Docx_2013);
    }
}

Create a Nested Table in Word in Java

Additional Info

  • tutorial_title: