Java 添加Word表格行或列

2025-10-20 07:05:10

1、方法1:通过eiceblue官网下载jar包。下载后,解压文件,并将lib文件夹下的Spire.Doc.jar文件导入到java程序。参考如下导入效果:

2、方法2:可通过maven仓库安装导入。

1、import com.spire.doc.*;

public class AddRow {

    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);

        table.addRow();//默认在表格最下方插入一行

        //table.addRow(4);//默认在表格最下方插入4个单元格数量的行

        //table.getRows().insert(2,table.addRow());//在表格中第三行插入一行

        //table.addRow(true,1);//带格式插入一行作为第2行

        //table.addRow(false,1);//不带格式插入一行作为第2行

        //保存文档

        doc.saveToFile("addrow.docx",FileFormat.Docx_2013);

        doc.dispose();

    }

}

2、表格行添加效果:

Java 添加Word表格行或列

1、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("test.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);

        }

        //保存文档

        doc.saveToFile("addcolumn.docx", FileFormat.Docx_2013);

        doc.dispose();

    }

}

2、表格列添加效果:

Java 添加Word表格行或列

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢