Not sure I understand your requirement correct. This is what I think you want: In your sheet, the data range starts in row 5 and column A determines the grouping. Now the need is getting the values of columns F and G for each group. Then the need is getting the first date for each group in column N and the last date for each group in column O.
So the need is to get the first row for each group and the last filled row for each group. Following example shows this. Mainly it uses a method int getNextFilledRow(Sheet sheet, int columnNum, int startRowNum)
to get the next filled row in a given column of the sheet starting on a given row number.
The code should only get the cells having the red marked contents in your given sheet.
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
class ReadExcelMergedCells {
static int getNextFilledRow(Sheet sheet, int columnNum, int startRowNum) {
int lastRow = sheet.getLastRowNum();
int nextFilledRow = lastRow;
for (int r = startRowNum; r <= lastRow; r++) {
nextFilledRow = r + 1;
Row row = sheet.getRow(nextFilledRow);
Cell cell = (row != null)?cell = row.getCell(columnNum):null;
if (cell != null && cell.getCellType() != CellType.BLANK) {
break;
}
}
return nextFilledRow;
}
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./Excel.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
int lastRow = sheet.getLastRowNum();
int startRow = 4;
Row row = null;
Cell cell = null;
int columnNum = -1;
int columNumA = 0; //column A determines the grouping
for (int r = startRow; r <= lastRow; r = getNextFilledRow(sheet, columNumA, r)) {
//r is the first row in this group
System.out.println("Group starting in row " + r);
//get cell in column F of first row in this group
columnNum = 5;
row = sheet.getRow(r);
cell = (row != null)?cell = row.getCell(columnNum):null;
System.out.println(cell);
//get cell in column G of first row in this group
columnNum = 6;
row = sheet.getRow(r);
cell = (row != null)?cell = row.getCell(columnNum):null;
System.out.println(cell);
//get cell in column N of first row in this group
columnNum = 13;
row = sheet.getRow(r);
cell = (row != null)?cell = row.getCell(columnNum):null;
System.out.println(cell);
//get cell in column O of last filled row in this group
columnNum = 14;
int lastRowInGroup = getNextFilledRow(sheet, columNumA, r) -1;
// get last filled cell in this group
for (int rl = lastRowInGroup; rl >= r; rl--) {
row = sheet.getRow(rl);
cell = (row != null)?cell = row.getCell(columnNum):null;
if (cell != null && cell.getCellType() != CellType.BLANK) {
break;
}
}
System.out.println(cell);
System.out.println("Group ending in row " + lastRowInGroup);
}
workbook.close();
}
}