4

我尝试在 java 中使用 apache poi 读取 excel 文件,但是 Eclipse 没有编译代码。

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 总是下划线Row row = rowIterator().next();。我不知道为什么?我该如何改进它?

4

3 回答 3

9

问题不在于eclipse,而在于代码。您不能将作为变量的 rowIterator 视为方法。您不能使用 () 语法调用变量。

尝试这个:

  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();
  }
于 2013-10-09T19:40:17.437 回答
6

您需要删除 rowIterator 之后的“()”。

代替:

rowIterator().next();

它应该是:

rowIterator.next()
于 2013-10-09T19:40:02.190 回答
5

在这一行:

Row row = rowIterator().next();

您正在尝试调用rowIterator在您自己的类上调用的方法,当然您没有。

从上下文中很明显,您的意思是指rowIterator您已经拥有的变量。将其更改为:

Row row = rowIterator.next();  // No () on rowIterator
于 2013-10-09T19:39:48.533 回答