16

xlsx使用 Apache POI API读取文件时如何获取最后一列的索引?

有一种getLastRowNum方法,但是我找不到与列数相关的任何内容...


编辑:我正在处理XLSX文件

4

4 回答 4

28

我认为您必须遍历行并检查HSSFRow.getLastCellNum()每一行。

于 2010-02-03T19:11:17.707 回答
14

检查每一行并调用Row.getLastCellNum()最大单元格编号是最后一列编号。

Row r = sheet.getRow(rowNum);
int maxCell=  r.getLastCellNum();
于 2016-09-01T20:12:39.760 回答
6

要了解具有任何行值的最后一列,首先您需要获取该行,然后您可以找到具有值的最后一列

句法 :

sheet.getrow(RowNumber).getLastCellNum();

RowNumber--> 是你想知道最后一列有值的行号

于 2017-01-15T02:47:19.040 回答
3

试试这个功能:

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();
    }
}
于 2018-03-06T13:08:20.097 回答