Java adds tables and nested tables in Word

As a visual communication mode and a method of organizing and organizing data, tables are widely used in various occasions and documents. Common tables can contain text, pictures and other elements. When we operate tables, we can insert pictures, nest tables, write text and format table styles. Next, you will create a table in a Word document through Java programming and implement formatting operations, including setting font, font size, font color, font thickness, etc., setting cell alignment, cell background color, cell merge / split, table border style, insert picture, etc.

Using tool: free flame.doc for Java (free version)
Jar file acquisition and import:
Method 1: through the official website download File package. After downloading, extract the file and import the Spire.Doc.jar file under the lib folder into the java program.
Method 2: install and import through maven warehouse, please refer to Import method.

Java code example

[example 1] add table

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import java.awt.*;

public class CreateTable {
    public static void main(String[] args){
        //Create Document object
        Document doc = new Document();
        Section sec = doc.addSection();

        //Declare array contents
        String[] header = {"class","Full name","Gender", "Student ID", "Professional achievement"};
        String[][] data =
                {
                        new String[]{"Class one","Wang Li", "female", "Y1256486", "138"},
                        new String[]{"Class one","Hong Fei Fei", "female", "Y5425875", "134"},
                        new String[]{"Class two","Liu Yang", "male", "B1546258", "141"},
                        new String[]{"Class three","Feng Gang", "male", "B1542367", "136"},
                        new String[]{"Class three","Liu Si Yuan", "male", "Z1263547", "133"},
                };

        //Add form
        Table table = sec.addTable(true);

        //Set the number of rows and columns in the table
        table.resetCells(data.length + 1, header.length);

        //Set the first row of the table as the header, write the contents of the header array, and format the header data
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(20);
        row.setHeightType(TableRowHeightType.Exactly);
        row.getRowFormat().setBackColor(Color.ORANGE);
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange range1 = p.appendText(header[i]);
            range1.getCharacterFormat().setFontName("Arial");
            range1.getCharacterFormat().setFontSize(12f);
            range1.getCharacterFormat().setBold(true);
            range1.getCharacterFormat().setTextColor(Color.white);
        }

        //Write the remaining group contents to the table and format the data
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            dataRow.getRowFormat().setBackColor(Color.white);
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
                range2.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                range2.getCharacterFormat().setFontName("Arial");
                range2.getCharacterFormat().setFontSize(10f);
            }
        }

        //Merge specified cells vertically
        table.applyVerticalMerge(0,1,2);
        table.applyVerticalMerge(0,4,5);

        //Insert picture into specified cell
        DocPicture dp = table.getRows().get(1).getCells().get(0).addParagraph().appendPicture("1.png");
        dp.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set cell background color
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 1; f < row2.getCells().getCount(); f++) {
                    row2.getCells().get(f).getCellFormat().setBackColor(new Color(144,238,144));
                }
            }
        }

        //Set table border style
        table.getTableFormat().getBorders().setBorderType(BorderStyle.Thick_Thin_Large_Gap);

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

Table adding effect:

[example 2] add nested table

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

public class NestedTable {
    public static void main(String[]args){
        //Load test document
        Document doc = new Document("sample.docx");

        //Gets the cells in the specified table and sets the row height and column width
Section sec = doc.getSections().get(0);
        Table table = sec.getTables().get(0);
        table.getRows().get(0).setHeight(120f);
        table.getRows().get(0).getCells().get(0).setWidth(380);

        //Add nested table to specified cell
        Table nestedtable = table.get(0,0).addTable(true);
        nestedtable.getTableFormat().setHorizontalAlignment(RowAlignment.Center);//Set alignment of nested tables in cells
        nestedtable.resetCells(4,4);//Specify the number of rows and columns in the nested table
        nestedtable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);//Set the content adaptive method of nested table
        //Declare table array contents
        String[][] data ={
                new String[]{"number","Producing area","Latest model","Date of manufacture",},
                new String[]{"1","A","V2.2.0","2019-06-21"},
                new String[]{"2","B","V2.6.1","2019-06-18"},
                new String[]{"3","C","V2.6.2","2019-06-14"},
        };

        //Fill array contents into nested tables
        for (int i = 0; i < data.length; i++) {
            TableRow dataRow = nestedtable.getRows().get(i);
            dataRow.getCells().get(i).setWidth(160);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            for (int j = 0; j < data[i].length; j++) {
                dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
                range.getCharacterFormat().setFontName("Regular script");
                range.getCharacterFormat().setFontSize(11f);
                range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            }
        }

        //Save document
        doc.saveToFile("nesedtable1.docx",FileFormat.Docx_2010);
    }
}

Nested table adding effect:

(end of this paper)

Tags: Java Programming Maven

Posted on Fri, 29 Nov 2019 08:18:19 -0800 by Yippee