所以我使用Apache POI库来读取Excel文件(.xlsx),我正在尝试做的很简单:我想遍历所有单元格,但只读取红色\黄色\绿色\蓝色的文本细胞,并跳过所有其他细胞 .

假设这个:

  • 加载的文件不为空并包含colorated cell,

  • 我导入了所有需要的库 .

按照指南(http://poi.apache.org/spreadsheet/quick-guide.html#Iterator),我最终编码:

...
...            
// why 15? 1400? no idea.. the guide doesn't explain... also isn't it dangerous??
         int rowStart = Math.min(15, sheet.getFirstRowNum());
         int rowEnd = Math.max(1400, sheet.getLastRowNum());

            // iterate through ROWS: 
            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {

                // returns 'rowNum' row of current sheet:
                Row r = sheet.getRow(rowNum); 
                if(r == null) {
                           System.out.println("empty row skipped");
                           continue;
                           }


                // iterate through CELLS: 
                for (Cell cell : r) {

                    if(cell == null) {
                        System.out.println("empty cell");
                        continue;
                        }

                        XSSFColor colore = (XSSFColor) cell.getCellStyle().getFillForegroundColorColor();

                        if (colore == null) {
                                System.out.println("something wrong?");
                                continue;
                            }
                            // checking colors like this:
                        if(colore.getARGBHex().substring(2, 5).equals("FFFF")){
                                // working on cell
                                continue;
                            }

                        if(colore.getARGBHex().substring(4, 5).equals("FF")){
                                // working on cell
                                continue;
                            }

                        if(colore.getARGBHex().substring(6, 7).equals("FF")){
                                // working on cell
                                continue;
                            }

                        if(colore.getARGBHex().substring(2, 3).equals("FF")){
                                // working on cell
                                continue;
                            }

                        }

当我执行代码时,它最终打印出“出错了?”千次,好像colore在所有细胞中都是无效的 . 所以问题是:

  • 为什么它alwais发现colore null? (我也试过.getFillBackgroundColorColor())

  • 是否有更聪明的方法来检查颜色而不是使用那些可怕的if语句?

提前致谢!