【发布时间】:2017-07-15 22:29:56
【问题描述】:
我正在尝试将第一个单元格中包含数据的每一行中的数据读入对象的 ArrayList。我的问题是我的代码似乎没有增加我的计数器超过第一行。我错过了一些简单的东西吗?
代码
try
{
wb = new XSSFWorkbook(new FileInputStream(fileName));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
XSSFSheet sheet = wb.getSheetAt(2);
ArrayList<Object> obj = new ArrayList<Object>();
int rowIndex = 0;
int cellIndex = 0;
XSSFRow row = sheet.getRow(rowIndex);
Iterator<Cell> rowItr = row.iterator();
while(rowIndex <= sheet.getLastRowNum())
{
if(row.getCell(0) == null)
{
continue;
}
else
{
while(rowItr.hasNext() && rowItr.next() != null)
{
XSSFCell cell = row.getCell(cellIndex);
if(cell == null)
{
continue;
}
else
{
obj.add(row.getCell(cellIndex).toString());
}
cellIndex++;
}
rowIndex++;
cellIndex = 0;
}
System.out.println(obj.toString());
}
rowIndex++;
}
}
输出
[ValuSmart Series 1120 Double Hung]
... 我得到这个输出 72 次,因为工作表中有 72 行
隔离循环
ArrayList<Object> obj = new ArrayList<Object>();
int rowCounter = 16;
int x = 0;
while(rowCounter <= 21)
{
XSSFRow row = sheet.getRow(rowCounter);
Iterator<Cell> rowItr = row.iterator();
while(rowItr.hasNext() && rowItr.next() != null)
{
XSSFCell cell = row.getCell(x);
if(cell == null)
{
continue;
}
else
{
obj.add(row.getCell(x).toString());
}
x++;
}
rowCounter++;
x = 0;
}
System.out.println(obj.toString());
【问题讨论】:
-
使用调试器并逐行执行代码将帮助您发现问题,并为您节省未来无数小时的调试时间。为什么不现在就开始做呢?
-
你的迭代器的目的是什么?
-
int rowIndex = 0; XSSFRow 行 = sheet.getRow(rowIndex);从技术上讲,您的“行”对象已经在循环外初始化,您只是在循环内使用相同的对象。
-
我的迭代器遍历行中的每个单元格,如果单元格不为空,则将其添加到 ArrayList 对象。 @shmosel
-
@YohannesGebremariam 你是在告诉我把这两行代码放在循环中吗?
标签: java while-loop apache-poi increment