使用Java获取给定excel中特定行的列数

mut*_*mar 34 java excel apache-poi

我想要excel中特定行的列数.怎么可能?我使用了POI API

但我只能将列数计算为7.

    try
            {
                fileInputStream = new FileInputStream(file);
                workbook = new HSSFWorkbook(fileInputStream);
                Sheet sheet = workbook.getSheet("0");


                int numberOfCells = 0;
                Iterator rowIterator = sheet.rowIterator();
                /**
                 * Escape the header row *
                 */
                if (rowIterator.hasNext())
                {
                    Row headerRow = (Row) rowIterator.next();
                    //get the number of cells in the header row
                    numberOfCells = headerRow.getPhysicalNumberOfCells();
                }
                System.out.println("number of cells "+numberOfCells);

}
Run Code Online (Sandbox Code Playgroud)

我希望特定行号的列数为10.excel列不相同

Abh*_*ngh 62

你可以做两件事

使用

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
Run Code Online (Sandbox Code Playgroud)

要么

int noOfColumns = sh.getRow(0).getLastCellNum();
Run Code Online (Sandbox Code Playgroud)

他们之间有一个很好的区别

  1. 选项1给出了实际填充内容的列数(如果没有填充10列的第2列,则会得到9)
  2. 选项2只提供最后一列的索引.因此完成'getLastCellNum()'

  • 根据[`getLastCellNum()`](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum()),已添加一个,所以你_shouldn' t_自己加一个. (2认同)