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);
                }
            }
        }
    }
}
相关推荐
攒了一袋星辰5 分钟前
SequenceGenerator高并发有序顺序号生成中间件 - 架构设计文档
java·后端·spring·中间件·架构·kafka·maven
lzp079111 分钟前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
Memory_荒年35 分钟前
TiDB:当 MySQL 遇上分布式,生了个“超级混血儿”
java·数据库·后端
asom2238 分钟前
DDD(领域驱动设计) 核心概念详解
java·开发语言·数据库·spring boot
大傻^2 小时前
LangChain4j Spring Boot Starter:自动配置与声明式 Bean 管理
java·人工智能·spring boot·spring·langchain4j
沐硕2 小时前
《基于改进协同过滤与多目标优化的健康饮食推荐系统设计与实现》
java·python·算法·fastapi·多目标优化·饮食推荐·改进协同过滤
愣头不青2 小时前
560.和为k的子数组
java·数据结构
共享家95272 小时前
Java入门(String类)
java·开发语言
l软件定制开发工作室2 小时前
Spring开发系列教程(34)——打包Spring Boot应用
java·spring boot·后端·spring·springboot
0xDevNull2 小时前
Spring Boot 循环依赖解决方案完全指南
java·开发语言·spring