17

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 with XLSX files

Gagravarr
  • 47,320
  • 10
  • 111
  • 156
marcosbeirigo
  • 11,098
  • 6
  • 39
  • 57

4 Answers4

28

I think you'll have to iterate through the rows and check HSSFRow.getLastCellNum() on each of them.

Henning
  • 16,063
  • 3
  • 51
  • 65
14

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();
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Helenice Silva
  • 141
  • 1
  • 2
6

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

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
3

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();
    }
}
  • 1
    Thanks 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. – Andre Hofmeister Mar 06 '18 at 13:26