java apache poi (part 2)

帅比萌擦擦* 提交于 2019-12-13 19:46:43

问题


cont. on java apache poi (part 1)

  • Code

    ...
    while(rowIterator.hasNext()){
        List<String> record = new ArrayList<String>();
    
        row = (XSSFRow)rowIterator.next();
    
        Iterator<Cell> cellIterator = row.cellIterator();
    
        while(cellIterator.hasNext()){
            cell = cellIterator.next();
            cell.setCellType(Cell.CELL_TYPE_STRING);
    
            switch(cell.getCellType()){
                case Cell.CELL_TYPE_STRING:
                    record.add(cell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    record.add(Double.toString
                    (cell.getNumericCellValue()));
                break;
            }
        }
        readFile();
    }
    
    public void readFile(){
        String ID = record.get(0);
        System.out.println(ID);
    }
    ...
    
  • From above code, my output is like below:
    ID
    1
    2
    3

  • My expected output should like this:
    1
    2
    3

  • My question is how to remove the first row from excel (ID) from the above code?


回答1:


To skip the first row:

while(rowIterator.hasNext()){

    row = (XSSFRow)rowIterator.next();

    if(row.getRowNum()==0) {
        continue;
    }

    List<String> record = new ArrayList<String>();
    Iterator<Cell> cellIterator = row.cellIterator();
    ...
    readFile();
}



回答2:


Add rowIterator.next(); above the While loop in the program which ignore the first row.So simple.Hope this helps you.

 **rowIterator.next();**
            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType())
                    {
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


来源:https://stackoverflow.com/questions/28755967/java-apache-poi-part-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!