How to get the last column index reading excel file?
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 num开发者_开发技巧ber of columns...
XLSX
filesI think you'll have to iterate through the rows and check HSSFRow.getLastCellNum()
on each of them.
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();
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
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();
}
}
精彩评论