我尝试在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();
行。我不知道为什么?我该如何改进呢?
答案 0 :(得分: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();
}
答案 1 :(得分:6)
您需要在rowIterator之后删除“()”。
而不是:
rowIterator().next();
应该是:
rowIterator.next()
答案 2 :(得分:5)
在这一行:
Row row = rowIterator().next();
您正在尝试在自己的班级上调用名为rowIterator
的方法,当然您没有。
从上下文中可以清楚地看出,您打算引用已有的rowIterator
变量。将其更改为:
Row row = rowIterator.next(); // No () on rowIterator