簡體   English   中英

如何在Java中使用apite poi中的rowiterator?

[英]How to use rowiterator in apache poi with java?

我嘗試在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(); 線。 我不知道為什么? 我怎樣才能改進它?

問題不在於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();
  }

您需要在rowIterator之后刪除“()”。

代替:

rowIterator().next();

它應該是:

rowIterator.next()

在這一行:

Row row = rowIterator().next();

您試圖在自己的類上調用一個名為rowIterator的方法,當然您沒有。

從上下文中可以清楚地看出,您的意思是引用您已經擁有的rowIterator變量。 將其更改為:

Row row = rowIterator.next();  // No () on rowIterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM