java获得excel最后一列,最后一行

最近遇到一个需求是需要向excel表格中追加数据,由于报表格式要求需要按列添加,因此需要获得excel表格最后一列值,然后列插入值:

  1. private static int findRealCloumns(XSSFSheet sheet, int... flag) {
  2.         int realCloumn = 0;
  3.         while (true) {
  4.             // 遍历行数,获取每行的最后一列
  5.             int total = 0;
  6.             for(int j : flag){
  7.                 XSSFRow row = sheet.getRow(j);
  8.                 if(row != null && row.getCell(realCloumn) != null && row.getCell(realCloumn).getCellType() < 6){
  9.                     row.getCell(realCloumn).setCellType(XSSFCell.CELL_TYPE_STRING);
  10.                 }
  11.                 if (row == null||row.getCell(realCloumn) == null||row.getCell(realCloumn).getStringCellValue().matches("^\\s+$")
  12.                         ||row.getCell(realCloumn).getCellType()>2) {
  13.                     total++;
  14.                 }
  15.                 // 如果需要列都是空说明就该返回
  16.                 if (total == flag.length) {
  17.                     return realCloumn;
  18.                 }
  19.             }
  20.             realCloumn++;
  21.         }
  22.     }

获得excel最后一行

  1. public static int findRealRows(XSSFSheet sheet, int... flag) {
  2.         int rowReal = 0;
  3.         int rows = sheet.getPhysicalNumberOfRows();// 此处物理行数统计有错误,
  4.         for (int i = 0; i < rows; i++) {
  5.             XSSFRow row = sheet.getRow(i);
  6.             int total = 0;
  7.             for(int j : flag){
  8.                 // 将所有单元格设置为字符串格式
  9.                 if(row != null && row.getCell(j) != null && row.getCell(j).getCellType() < 6){
  10.                     row.getCell(j).setCellType(XSSFCell.CELL_TYPE_STRING);
  11.                 }
  12.                 if (row == null ||row.getCell(j) == null||row.getCell(j).getStringCellValue().matches("^\\s+$")||row.getCell(j).getCellType()>2) {
  13.                     total++;
  14.                     
  15.                 }
  16.             }
  17.             // 如果需要列都是空说明就该返回
  18.             if (total == flag.length) {
  19.                 return rowReal;
  20.             } else {
  21.                 rowReal++;
  22.             }
  23.         }
  24.         return rowReal;
  25.     }

总结 :

       不论是excel最后一行还是最后一列,首先需要约定一行的前几个单元格内容不能为空或者一列的前几行单元格不能为空,否则判断该行或该列为最后一行或列。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值