简体   繁体   中英

Using apache poi how to read a specific excel rows and column

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()+"|| ");

        }       
    }
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM