我正在阅读excel工作簿中的多张数据
我能够从多张纸上读取数据,但我正在尝试打印特定纸张数据" n" 次。
例如:我的工作簿包含10张编号为1-10的工作表,我想打印"工作表1"数据3次,"表2"数据3次..
同样,我将打印每个工作表数据" n" 次。
变量:
名称 - 包含工作表名称,出现次数 - 包含要打印的工作表数据的次数。
String[] name = { "a", "b", "c" };
int[] occurances = { 2, 3, 4 };
int c1 = 0;
int c2 = 0;
Excel文件阅读代码:
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet datatypeSheet = workbook.getSheetAt(i);
Iterator<Row> iterator = datatypeSheet.iterator();
if (datatypeSheet.getSheetName().equals(name[c1])) {
c1++;
for (int d = 0; d < occurances[c2]; d++) {
c2++;
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell
.getStringCellValue() + "--");
}
}
System.out.println();
}
}
}
}
我试过,但是我打印了所有的纸张数据一次
请帮忙!
答案 0 :(得分:0)
您的代码存在一些问题。了解代码无法正常工作的最佳方法是调试(通过IDE或通过日志记录)。
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
// if your sheets are not in 'a', 'b', 'c' order this code
// will not work. think why
Sheet datatypeSheet = workbook.getSheetAt(i);
if (datatypeSheet.getSheetName().equals(name[c1])) {
c1++;
// you need this variable to be fixed for your loop
int occurancesForSheet = occurances[c2++];
for (int d = 0; d < occurancesForSheet; d++) {
// you need a new iterator each time
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell
.getStringCellValue() + "--");
}
}
System.out.println();
}
}
}
}