How to get the last column index reading excel file?
52,169
Solution 1
I think you'll have to iterate through the rows and check HSSFRow.getLastCellNum()
on each of them.
Solution 2
Check each Row and call Row.getLastCellNum()
the max cell number is the last column number.
Row r = sheet.getRow(rowNum);
int maxCell= r.getLastCellNum();
Solution 3
To get to know the last column that has value of any row , First you need to get the row and then you can find the last column that has value
Syntax :
sheet.getrow(RowNumber).getLastCellNum();
RowNumber
--> is the row number for which you want to know the last column that has value
Solution 4
Try this function:
private void maxExcelrowcol() {
int row, col, maxrow, maxcol;
//Put file name here for example filename.xls
String filename = "filename.xls";
static String TAG = "ExelLog";
//you can use 'this' in place of context if you want
Context context = getApplicationContext();
try {
// Creating Input Stream
File file = new File(context.getExternalFilesDir(null), filename);
FileInputStream myInput = new FileInputStream(file);
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
//Row iterator
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
//Cell iterator for iterating from cell to next cell of a row
Iterator cellIter = myRow.cellIterator();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
row = myCell.getRowIndex();
col = myCell.getColumnIndex();
if (maxrow < row) {
maxrow = row;
}
if (maxcol < col) {
maxcol = col;
}
}
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
Author by
marcosbeirigo
Updated on July 09, 2022Comments
-
marcosbeirigo almost 2 years
How do i get the index of the last column when reading a
xlsx
file using the Apache POI API?There's a
getLastRowNum
method, but I can't find nothing related to the number of columns...
EDIT: I'm dealing withXLSX
files -
Jorge Rocha over 9 yearsFor XLSX files the only thing you have to change is HSSF to XSSF. XSSFRow.getLastCellNum()
-
Andre Hofmeister over 6 yearsThanks for your answer. It would be great if you would also add a few comments to your code. This helps people to understand your answer better.