【发布时间】:2017-01-07 17:27:12
【问题描述】:
我在使用 java 对 excel 中的行和单元格进行迭代时遇到问题。我以这种方式在表格中构建了数据:
我必须收集所有数字并将其传递给构造函数。我试过这样:
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()){
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
int id = (int) cellIterator.next().getNumericCellValue();
int pr = (int) cellIterator.next().getNumericCellValue();
int[] prId = new int[2];
prId[0] = (int) cellIterator.next().getNumericCellValue();
iterator.next(); // i have to move down one row to get 5 and 6
precId[1] = // what should I type here?? cellIterator.next() will cause, that cell with value "5" will be omitted and I will get "6"
int co = (int) cellIterator.next().getNumericCellValue();
list.add(new Rule(id, pr, prId, co));
}
如何处理? 在此先感谢:)
编辑:
我决定以其他方式获取细胞:
for(int rowNum = rowStart+1; rowNum < rowEnd; rowNum++){
Row r = sheet.getRow(rowNum);
if(r == null){
continue;
}
int lastColumn = Math.max(r.getLastCellNum(), 4);
for(int cn = 0; cn < lastColumn; cn++){
@SuppressWarnings("deprecation")
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if(c == null){
continue;
}else{
System.out.println(c);
}
}
}
这个解决方案显然更好,但我有问题,因为不是通过System.out.println(c) 显示单元格值我需要将此值传递给构造函数,如使用迭代器的示例中所示。但是现在我可以使用循环访问单元格,所以我无法使用 .next() 或类似的东西获取下一个单元格的值 - 我无法在一行代码中获取下一个单元格,所以如何创建相同的对象如上(使用迭代器)但使用此代码?
【问题讨论】:
-
“如何在不前进的情况下获取单元格值”在继续之前存储值?
-
@1blustone 我不知道如何获得这个值。阅读我的解释,不仅仅是标题:)
-
我做到了,这就是为什么我说要存储它。迭代器继续前进有什么问题?有一个像
Cell stored = cellIterator.next()这样的行,然后将它用于precId[1]?还是我没听明白 -
为什么不直接使用单元格索引而不是Iterator来读取单元格值
-
@1blustone 当我在值为 3 的单元格上时,我必须向下移动行以获得 5 和 6 对吗?所以我使用
iterator.next();。现在必须获得值为 5 的单元格,但是当我调用cellIterator.next()时,我会忽略此单元格,而我会获得值为 6 的单元格。这是因为 celliteretor 指向值为 3 的列(这与值 5) 这就是为什么我不能使用 .next() 因为我会丢失值为 5 的单元格。
标签: java excel apache apache-poi cell