Reputation: 377
hi i want to search a string in a first row, if string is found then i want to move that column.
for (int i = 0; i < 1; i++) {
Row row = firstSheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
String rtm=row.getCell(j).getStringCellValue();
if(rtm.contains(text)){
System.out.println(row.getCell(j).getStringCellValue()+"|| ");
}
}
}
Upvotes: 1
Views: 4305
Reputation: 48326
The problem is with your very first line:
for (int i = 0; i < 1; i++) {
This will only run the loop once, which is why you are only getting the first row!
Your code will also fail for non-string cells, eg numeric cells.
I would suggest you take some time to read the Apache POI documentation on iterating over rows and cells. Then you probably want something more like:
System.out.println("Searching for cells containing '" + text + "'");
DataFormatter formatter = new DataFormatter();
for (Sheet sheet : wb ) {
for (Row row : sheet) {
for (Cell cell : row) {
String value = formatter.formatCellValue(cell);
if (value.contains(text)) {
System.out.println("Found at " + (new CellReference(cell)).formatAsString() + ":");
System.out.println(value);
}
}
}
}
That will handle non-string cells, and would give you output like:
Searching for cells containing 'needle'
Found at A5
This is a needle
Found at B10
A needle can be helpful
Then tweak as needed!
Upvotes: 2