温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

发布时间:2020-08-09 22:42:51 来源:ITPUB博客 阅读:246 作者:Mia张 栏目:编程语言

概述

表格作为一种可视化交流模式及组织整理数据的手段,在各种场合及文档中应用广泛。常见的表格可包含文字、图片等元素,我们操作表格时可以插入图片、写入文字及格式化表格样式等。下面,将通过Java编程在Word文档中创建表格或者嵌套表格,并实现格式化操作,包括设置字体、字号、字体颜色、字体粗细等,设置单元格对齐方式、单元格背景色、单元格合并、设置表格边框样式、插入图片等。另外,本文也将介绍对表格中的行或者列的一些操作,包括添加行或列、复制行或列以及设置表格是否跨页断行等。

使用工具

  • Free Spire.Doc for Java (免费版)

jar文件获取及导入:

Jar文件可通过e-iceblue中文 官网获取,下载后,解压文件,将lib文件夹下的Spire.Doc.jar导入Java程序;也可以通过maven仓库安装导入 参考 导入方法 导入效果如下:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

Java代码示例(供参考)

1. 创建表格
 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){
         //创建Document对象
         Document doc = new Document();
         Section sec = doc.addSection();
 
         //声明数组内容
         String[] header = {"班级","姓名","性别", "学号", "专业成绩"};
         String[][] data =
                 {
                         new String[]{"一班","王丽", "女", "Y1256486", "138"},
                         new String[]{"一班","洪菲菲", "女", "Y5425875", "134"},
                         new String[]{"二班","刘洋", "男", "B1546258", "141"},
                         new String[]{"三班","冯刚", "男", "B1542367", "136"},
                         new String[]{"三班","刘思源", "男", "Z1263547", "133"},
                 };
 
         //添加表格
         Table table = sec.addTable(true);
 
         //设置表格的行数和列数
         table.resetCells(data.length + 1, header.length);
 
         //设置表格第一行作为表头,写入表头数组内容,并格式化表头数据
         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);
         }
 
         //写入剩余组内容到表格,并格式化数据
         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);
             }
         }
 
         //纵向合并指定单元格
         table.applyVerticalMerge(0,1,2);
         table.applyVerticalMerge(0,4,5);
 
         //插入图片到指定单元格
         DocPicture dp = table.getRows().get(1).getCells().get(0).addParagraph().appendPicture("1.png");
         dp.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
 
         //设置单元格背景颜色
         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));
                 }
             }
         }
 
         //设置表格边框样式
         table.getTableFormat().getBorders().setBorderType(BorderStyle.Thick_Thin_Large_Gap);
 
         //保存文档
         doc.saveToFile("CreateTable.docx", FileFormat.Docx_2013);
     }
 }

表格创建效果:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

2. 创建嵌套表格
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);
    }
}

嵌套表格添加效果:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

3. 在Word表格中添加行或者列

  3.1 添加行

import com.spire.doc.*;
public class AddRow {
    public static void main(String[] args){
        //加载测试文档
        Document doc = new Document();
        doc.loadFromFile("sample.docx");
        //获取表格
        Section section = doc.getSections().get(0);
        Table table = section.getTables().get(0);
        table.addRow();//默认在表格最下方插入一行
        //table.getRows().insert(2,table.addRow());//在表格中第3行插入一行
        //table.addRow(4);//默认在表格最下方添加4个单元格
        //table.addRow(true,2);//带格式在最后一行添加2个单元格
        //table.addRow(false,2);//不带格式在最后一行添加2个单元格
        //保存文档
        doc.saveToFile("addrow.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

行添加效果:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

  3.2 添加列

import com.spire.doc.*;
import com.spire.doc.documents.BorderStyle;
import java.awt.*;
public class AddColumn {
    public static void main(String[] args){
        //加载测试文档
        Document doc = new Document();
        doc.loadFromFile("sample.docx");
        //获取表格
        Section section = doc.getSections().get(0);
        Table table = section.getTables().get(0);
        //获取表格单元格宽度及类型
        float width = table.get(0,0).getWidth();
        CellWidthType type = table.get(0,0).getCellWidthType();
        
        //遍历表格每一行
        for (int i = 0; i < table.getRows().getCount(); i++) {
            TableRow row = table.getRows().get(i);//获取表格每一行
            Color color = row.getCells().get(0).getCellFormat().getBackColor();//获取表格单元格背景色
            //基于表格每行,在最后添加一个单元格,并设置单元格格式
            TableCell cell = row.addCell(true);//默认在最后一列添加单元格
            cell.setWidth(width);
            cell.setCellWidthType(type);
            cell.getCellFormat().getBorders().setBorderType(BorderStyle.Single);
            cell.getCellFormat().setBackColor(color);
            //如需在指定位置插入列,基于以上代码并增加下面一行代码即可
            //row.getCells().insert(2,cell);//插入一列作为第三列
        }
        //保存文档
        doc.saveToFile("addcolumn.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}

列添加效果:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

4. 复制表格行或者列

  4.1 复制行

import com.spire.doc.*;
public class CopyRow {
    public static void main(String[] args) {
        //加载测试文档
        Document doc = new Document();
        doc.loadFromFile("test.docx");
        //获取表格
        Section section = doc.getSections().get(0);
        Table table =section.getTables().get(0);
        //复制第三行,并将复制后的行插入到表格作为第五行
        TableRow row = table.getRows().get(2).deepClone();
        table.getRows().insert(4,row);
        //保存文档
        doc.saveToFile("CopyRow.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

表格行复制效果:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

 4.2 复制列

import com.spire.doc.*;
public class CopyColumn {
    public static void main(String[] args) {
       //加载测试文档
        Document doc = new Document();
        doc.loadFromFile("test.docx");
        //获取表格
        Section section = doc.getSections().get(0);
        Table table =section.getTables().get(0);
        //遍历表格每行
        for (int i = 0; i < table.getRows().getCount(); i++) {
            //复制表格中每行的最后一个单元格,复制
            TableRow row = table.getRows().get(i);
            TableCell cell = (TableCell) row.getCells().getLastItem().deepClone();
            //row.getCells().add(cell);//默认在每行最后添加复制后的单元格
            row.getCells().insert(2,cell);//在指定位置插入复制后的单元格
        }
        //保存文档
        doc.saveToFile("CopyColumn1.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

表格列复制效果:

Java 创建Word表格/嵌套表格、添加/复制表格行或列、设置表格跨页断行

5. 设置Word表格是否禁止跨页断行

这里通过两种方式来设置防止表格跨页出现断行的效果,供参考。

  1. 设置属性禁止跨页断行

import com.spire.doc.*;
public class PreventPagebreak {
    public static void main(String[]args){
        //加载测试文档
        Document doc= new Document("test.docx");
        //获取表格
        Table table = doc.getSections().get(0).getTables().get(0);
        //设置表格是否分页断行
        table.getTableFormat().isBreakAcrossPages(false);
        //保存文档
        doc.saveToFile("result.docx",FileFormat.Docx_2013);
    }
}

  2. 保持表格内容在同一页面

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
public class PreventPagebreak {
    public static void main(String[]args){
        //加载测试文档
        Document doc= new Document("test.docx");
        //获取表格
        Table table = doc.getSections().get(0).getTables().get(0);
        //遍历表格单元格
        for (int i = 0;i< table.getRows().getCount();i++) {
            TableRow rows = table.getRows().get(i);
            for (int j = 0; j< rows.getCells().getCount(); j++){
                for (int z= 0; z < rows.getCells().get(j).getParagraphs().getCount();z++){
                    Paragraph p = rows.getCells().get(j).getParagraphs().get(z);
                    p.getFormat().setKeepFollow(true);//设置表格内容在同一页显示
                }
            }
        }
        //保存文档
        doc.saveToFile("result1.docx",FileFormat.Docx_2013);
    }
}

(本文完)

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI