Why I cannot get values from excel into a list usi

2019-08-27 02:52发布

问题:

I would like to gather the relevant Excel cells into a list for a sequence comparison. However, I failed to get those cell values with conditions into the list by using below codes (nothing is printed in console as expected).

I tried using startsWith and other condition syntax but I am not sure if this is the issue or I did sth wrong in prior.

    HSSFSheet dispcolsheet = workbook2.getSheet(0);
    Iterator<Row> colRowItr = dispcolsheet.rowIterator();
    List<String> colstatuslist = new ArrayList<String>();
    while (colRowItr.hasNext()){
        Row row = colRowItr.next();
        Cell colname = row.getCell(0);
        if ("ABC_".contains(colname.getStringCellValue())) {
            colstatuslist.add(row.getCell(1).getStringCellValue());
            System.out.println(colstatuslist);
        }
    }

My xls file looks like:

name   |status
ABC_1  | TRUE
ABC_2  | FALSE
ABC_3  | TRUE
.
.
.

I expect to store the TRUE FALSE TRUE from column B in sequence so that I could get() them to use for comparison, like get(0) would be the status of ABC_1 as TRUE, get(1) would be the status of ABC_2 as FALSE and so on.

Thank you.

回答1:

You are doing the if check the wrong direction/way.

With

"ABC_".contains(colname.getStringCellValue())

You are checking if the string ABC_ contains (or has) the cell value.

Does ABC_ contain ABC_1 - No

You should reverse it as

colname.getStringCellValue().contains("ABC_") 

or 
colname.getStringCellValue().startsWith("ABC_")

Does ABC_1 contain/startsWith ABC_ - Yes



回答2:

I find it best to use StringUtils for String comparisons. You can do,

StringUtils.contains(colname.getStringCellValue(), "ABC_") 
StringUtils.containsIgnoreCase(colname.getStringCellValue(), "ABC_") 

Very simple.