How to use rowiterator in apache poi with java?

Aleksei Nikolaevich picture Aleksei Nikolaevich · Oct 9, 2013 · Viewed 36.4k times · Source

I tried to read an excel file using apache poi in java, however, Eclipse did not compile the code.

public class ReadExcel {

    public static void main(String[] args) throws IOException {

        FileInputStream file = new FileInputStream(new File("C:\\Users\\XXXXXXXXXXXXXXXXal\\042012.xls"));
        HSSFWorkbook wb = new HSSFWorkbook(file);
        HSSFSheet sheet = wb.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {

        Row row = rowIterator().next();      \\ THIS LINE GETS UNDERLINED BY ECLIPSE!!!
         Iterator<Cell> cellIterator = row.cellIterator();
            while(cellIterator.hasNext()) {

                Cell cell = cellIterator.next();

                        System.out.print(cell.getStringCellValue() + "\t\t");

                            }

        }
        file.close();
        FileOutputStream out =
            new FileOutputStream(new File("C:\\test.xls"));
        wb.write(out);
        out.close();
        }


    }

Eclipse always underlines Row row = rowIterator().next(); line. I do not know why? How can I improve it?

Answer

axiopisty picture axiopisty · Oct 9, 2013

The problem is not with eclipse, it is with the code. You can not treat rowIterator which is a variable, as a method. You can not invoke a variable with the () syntax.

Try this:

  public static void main(String[] args) throws IOException {
    FileInputStream file = new FileInputStream(new File("C:\\Users\\XXXXXXXXXXXXXXXXal\\042012.xls"));
    HSSFWorkbook wb = new HSSFWorkbook(file);
    HSSFSheet sheet = wb.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
      Row row = rowIterator.next();
      Iterator <Cell> cellIterator = row.cellIterator();
      while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        System.out.print(cell.getStringCellValue() + "\t\t");
      }
    }
    file.close();
    FileOutputStream out =
      new FileOutputStream(new File("C:\\test.xls"));
    wb.write(out);
    out.close();
  }