¿Cómo obtener el último índice de la columna leer el archivo de Excel?
-
25-09-2019 - |
Pregunta
¿Cómo puedo obtener el índice de la última columna cuando se lee un archivo de xlsx
mediante la API de Apache POI?
No es un método getLastRowNum
, pero no puedo encontrar nada relacionado con el número de columnas ...
EDITAR:
Estoy tratando con archivos XLSX
Solución
Creo que tendrá que iterar a través de las filas y de verificación HSSFRow.getLastCellNum()
en cada uno de ellos.
Otros consejos
Comprobar cada fila y Row.getLastCellNum()
llamada el número de células max es el último número de la columna.
Row r = sheet.getRow(rowNum);
int maxCell= r.getLastCellNum();
Para conocer la última columna que tiene un valor de cualquier fila, primero que necesita para obtener la fila y luego se puede encontrar la última columna que tiene un valor
Sintaxis:
sheet.getrow(RowNumber).getLastCellNum();
RowNumber
-> es el número de fila para la que desea conocer la última columna que tiene un valor
Trate de esta función:
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();
}
}