使用Java获取给定excel中特定行的列数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18489817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get number of columns of a particular row in given excel using Java
提问by muthukumar
I want the number of columns of a particular row in excel. How is that possible? I used POI API
我想要excel中特定行的列数。这怎么可能?我使用了 POI API
but I could get only columns count to 7 .
但我只能得到列数为 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);
}
I want the number of columns at a particular row number say 10 . The excel columns are not same
我想要特定行号的列数说 10 。excel列不一样
采纳答案by Abhishek Singh
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
它们之间有细微的差别
- 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)
- Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'
- 选项 1 给出了实际填充内容的列数(如果 10 列的第 2 列未填充,您将得到 9)
- 选项 2 只为您提供最后一列的索引。因此完成了'getLastCellNum()'
回答by Kyrylo Semenko
/** 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;
}