Java操作word表格

文章目录


使用工具:Free Spire.Doc for Java (免费版)

添加Word嵌套表格
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;


public class NestedTable {
    
    
    public static void main(String[]args){
    
    
        //加载测试文档
        Document doc = new Document("sample.docx");
        
        //获取指定表格中的单元格,并设置行高、列宽
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);

        //添加嵌套表格到指定单元格
        Table nestedtable = table.get(0,0).addTable(true);
        nestedtable.getTableFormat().setHorizontalAlignment(RowAlignment.Center);//设置嵌套表格在单元格中的对齐方式
        nestedtable.resetCells(4,4);//指定嵌套表格行数、列数
        nestedtable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);//设置嵌套表格内容自适应方法
        //声明表格数组内容
        String[][] data ={
    
    
                new String[]{
    
    "编号","产区","最新型号","生产日期",},
                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"},
        };

        //填充数组内容到嵌套表格
        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("楷体");
                range.getCharacterFormat().setFontSize(11f);
                range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            }
        }

        //保存文档
        doc.saveToFile("nesedtable1.docx",FileFormat.Docx_2010);
    }
}

参考:

https://www.cnblogs.com/Yesi/p/11691132.html

猜你喜欢

转载自blog.csdn.net/weixin_38323645/article/details/108742337