java操作word里的表格

发布于:2025-06-16 ⋅ 阅读:(21) ⋅ 点赞:(0)
依赖:
<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);
                }
            }
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到