Frage

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?

War es hilfreich?

Lösung

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();
  }

Andere Tipps

You need to remove the "()" after rowIterator.

Instead of:

rowIterator().next();

It should be:

rowIterator.next()

In this line:

Row row = rowIterator().next();

You are attempting to call a method called rowIterator on your own class, which of course you don't have.

From the context it's clear you meant to refer to the rowIterator variable you already have. Change it to:

Row row = rowIterator.next();  // No () on rowIterator
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top