Reputation: 119
I have one for loop with another loop inside, the first loop sets the row and the second loop reads thru 4 cells, the first time the loop runs it works well but after that im guessing its not changing rows because it just repeats the result from the first loop but without showing the cell value, here is the code:
for(int k=1; k<=2; k++){
XSSFRow row1 = worksheet.getRow(e);
System.out.println("Row: "+e);
e++;
for(int i=0;i<Oleo18_1.size();i++){
XSSFCell c = row1.getCell((short) d);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
Oleo18_1.set(i, false);
}
else {
Oleo18_1.set(i, true);
c.setCellType(Cell.CELL_TYPE_STRING);
}
if(Oleo18_1.get(i) == true){
values_18_1.set(i, 9.09090909);
}
String a1Val = c.getStringCellValue();
System.out.println("valor ponderacion"+(d+1)+": "+values_18_1.get(i));
System.out.println("valor celda "+(d+1)+": "+a1Val);
d++;
}
}
Upvotes: 0
Views: 1486
Reputation: 2466
So, with Apache POI the simplest way to iterate over cells is to use the prompt from the Busy Developers Guide which demonstrates iterating in a for-each loop because the rows are iterable like this:
Iterate over rows and cells
Sometimes, you'd like to just iterate over all the rows in a sheet, or all the >cells in a row. This is possible with a simple for loop.
Luckily, this is very easy. Row defines a CellIterator inner class to handle iterating over the cells (get one with a call to row.cellIterator()), and Sheet provides a rowIterator() method to give an iterator over all the rows. These implement the java.lang.Iterable interface to allow foreach loops.
Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { // Do something here } }
The most important part of this is actually "grabbing" the correct sheet as you can see in this first line of the code snippet and iterating over the desired portion rather than specifying the row at which you want to start. Instead you want to selectively manipulate your data as below:
private void startParsing() {
for (int i = 0; i < worksheet.getPhysicalNumberOfRows(); i++) {
if (i == ROW_E || i == ROW_F) {
mutateCell(worksheet.getRow(i));
}
}
}
private void mutateCell(final Row curRow) {
for(int i=0;i<Oleo18_1.size();i++){
XSSFCell c = curRow.getCell((short) d);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
Oleo18_1.set(i, false);
}
else {
Oleo18_1.set(i, true);
c.setCellType(Cell.CELL_TYPE_STRING);
}
if(Oleo18_1.get(i) == true){
values_18_1.set(i, 9.09090909);
}
String a1Val = c.getStringCellValue();
System.out.println("valor ponderacion"+(d+1)+": "+values_18_1.get(i));
System.out.println("valor celda "+(d+1)+": "+a1Val);
d++;
}
}
Upvotes: 2