get number of columns of a particular row in given excel using Java

后端 未结 3 1831
忘掉有多难
忘掉有多难 2020-12-13 13:41

I want the number of columns of a particular row in excel. How is that possible? I used POI API

but I could get only columns count to 7 .

    try
           


        
相关标签:
3条回答
  • 2020-12-13 13:50

    Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
    I used the method below to get the last column index that contains an actual value.

    private int getLastFilledCellPosition(Row row) {
            int columnIndex = -1;
    
            for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
                Cell cell = row.getCell(i);
    
                if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                    continue;
                } else {
                    columnIndex = cell.getColumnIndex();
                    break;
                }
            }
    
            return columnIndex;
        }
    
    0 讨论(0)
  • 2020-12-13 14:04
    /** Count max number of nonempty cells in sheet rows */
    private int getColumnsCount(XSSFSheet xssfSheet) {
        int result = 0;
        Iterator<Row> rowIterator = xssfSheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            List<Cell> cells = new ArrayList<>();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                cells.add(cellIterator.next());
            }
            for (int i = cells.size(); i >= 0; i--) {
                Cell cell = cells.get(i-1);
                if (cell.toString().trim().isEmpty()) {
                    cells.remove(i-1);
                } else {
                    result = cells.size() > result ? cells.size() : result;
                    break;
                }
            }
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-13 14:13

    There are two Things you can do

    use

    int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
    

    or

    int noOfColumns = sh.getRow(0).getLastCellNum();
    

    There is a fine difference between them

    1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
    2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'
    0 讨论(0)
提交回复
热议问题