java操作word里的表格

复制代码
依赖:
<dependency>
    <groupId>com.techCoLtd</groupId>
    <artifactId>aspose-words-16.4.0-jdk16</artifactId>
    <classifier>jdk16</classifier>
</dependency>

/**
 * 删除表格及表格的行
 * @throws Exception
 */
private static void deletedTable() throws Exception {
    Document doc = new Document("表格路径");
    Table table = doc.getFirstSection().getBody().getTables().get(0);
    // 删除整个表的方法
    table.remove();
    // 删除某一行 的方法
    if (table.getRows().getCount() > 1) { // 确保至少有两行才进行删除操作
        table.getRows().removeAt(0);// 删除第一行
    }

    doc.save("D:\\work\\save\\ceshi.docx");
}
复制代码
/**
 *
 * 读取表格的内容
 * @throws Exception
 */
public static void readTableTxtByIndex() throws Exception {
    Document doc = new Document("表格路径");
    //获取所有的表格
    NodeCollection tableNodes = doc.getChildNodes(NodeType.TABLE, true);
    int tableCount = tableNodes.getCount();
    System.out.println("表格数量:{}"+ tableCount);
    for (int i = 0; i < tableCount; i++) {
        Table table = (Table)tableNodes.get(i);
        //按表格索引 单独写逻辑进行数据的读取 本示例中就1个表格 因此就放1个逻辑进行解析了
        if(0 == i){
            //获取表格中的所有行节点
            RowCollection rows = table.getRows();
            int rowCount = rows.getCount();
            System.out.println("共有表格行:{}" + rowCount);
            //获取每一行的单元格节点
            for (int j = 0; j < rowCount; j++) {
                Row row = rows.get(j);
                CellCollection cells = row.getCells();
                int cellsCount = cells.getCount();
                System.out.println("第" + j + "行有" + rowCount + "个单元格{}");
                for (int k = 0; k < cellsCount; k++) {
                    Cell cell = cells.get(k);
                    String cellText = cell.getText();
                    System.out.println("第" + j + "行 第" + k + "个单元格的文本:{}" + cellText);
                }
            }
        }
    }
}
相关推荐
d_dreamer3 分钟前
SeaTunnel推荐Maven版本
java·maven
清心歌14 分钟前
记一次系统环境变量更改后在IDEA中无法读取新值的排查过程
java·后端·intellij-idea·idea
大尚来也17 分钟前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
dong__csdn20 分钟前
jdk添加信任证书
java·开发语言
hhcccchh34 分钟前
1.1 HTML 语义化标签(header、nav、main、section、footer 等)
java·前端·html
随风,奔跑37 分钟前
Spring Security
java·后端·spring
yaaakaaang1 小时前
十二、代理模式
java·代理模式
花千树-0101 小时前
Java 接入多家大模型 API 实战对比
java·开发语言·人工智能·ai·langchain·ai编程
卓怡学长1 小时前
m326数据结构课程网络学习平台的设计与实现+vue
java·spring·tomcat·maven·intellij-idea·mybatis
han_hanker2 小时前
@Validated @Valid 用法
java·spring boot