Try this:
private void excelReader() {
String data;
try {
InputStream is = new FileInputStream("Read.xlsx");
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
Row r = (Row)rowIter.next();
short lastCellNum = r.getLastCellNum();
int[] dataCount = new int[lastCellNum];
int col = 0;
rowIter = sheet.rowIterator();
while(rowIter.hasNext()) {
Iterator cellIter = ((Row)rowIter.next()).cellIterator();
while(cellIter.hasNext()) {
Cell cell = (Cell)cellIter.next();
col = cell.getColumnIndex();
dataCount[col] += 1;
DataFormatter df = new DataFormatter();
data = df.formatCellValue(cell);
System.out.println("Data: " + data);
}
}
is.close();
for(int x = 0; x < dataCount.length; x++) {
System.out.println("col " + x + ": " + dataCount[x]);
}
}
catch(Exception e) {
e.printStackTrace();
return;
}
}
Tested code
I created an xlsx file with the following cell data:
Col0 Col1 Col2 Col3 Col4
1 a x a q
2 b y s w
3 c z d e
4 d f r
5 e t
y
The contents of dataCount array is this:
col 0: 6
col 1: 6
col 2: 4
col 3: 5
col 4: 7
The numbers on the right count the number of cells with data for each column, including the header row.
If you want to exclude the header row, just remove the line:
rowIter = sheet.rowIterator();
just before the while loop.
Is this what you are looking for?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…