尝试读取excel,其中需要在一列中提取行数,其中包含除空白或空单元格外的数据或值。并将单元格值存储在字符串数组中,我尝试使用sheet.getLastRowNum(),但没有对我起作用。有人能建议出路吗。
以下是我迄今所做的尝试
private void readExcel()
{
InputStream ExcelFileToRead = new FileInputStream("C:/Users/Public/template.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row=null;
XSSFCell cell;
String[] strArray=null;
int i=10;
for(i=10;i<this.sheet.getLastRowNum();i++)
{
if( (getCell("G"+i)!=null) )
{
strArray[index]= strArray[index] + getCell("G"+i).toString() ;
}
}
System.out.println(strArray);
}
private XSSFCell getCell(String cellName)
{
Pattern r = Pattern.compile("^([A-Z]+)([0-9]+)$");
Matcher m = r.matcher(cellName);
if(m.matches())
{
String columnName = m.group(1);
int rowNumber = Integer.parseInt(m.group(2));
if(rowNumber > 0)
{
return wb.getSheetAt(0).getRow(rowNumber-1).getCell(CellReference.convertColStringToIndex(columnName));
}
}
return null;
}
发布于 2019-11-08 08:26:19
比公认的答案更好的版本:
public static int getNumberOfNonEmptyCells(XSSFSheet sheet, int columnIndex) {
int numberOfNonEmptyCells = 0;
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
if (row != null) {
XSSFCell cell = row.getCell(columnIndex);
if (cell != null && cell.getCellType() != CellType.BLANK && !cell.getRawValue().trim().isEmpty()) {
numberOfNonEmptyCells++;
}
}
}
return numberOfNonEmptyCells;
}
这种方法有两个优点:
由于我无法上载工作簿,下面是工作表的xml部分,它破坏了接受的方法:
<?xml version="1.0" encoding="UTF-8"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac">
<dimension ref="A1:A5" />
<sheetViews>
<sheetView tabSelected="1" workbookViewId="0">
<selection activeCell="A3" sqref="A3" />
</sheetView>
</sheetViews>
<sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25" />
<sheetData>
<row r="1" spans="1:1" x14ac:dyDescent="0.25">
<c r="A1">
<v>1</v>
</c>
</row>
<row r="2" spans="1:1" x14ac:dyDescent="0.25">
<c r="A2">
<v>2</v>
</c>
</row>
<row r="3" spans="1:1" x14ac:dyDescent="0.25">
<c r="A3">
<v></v>
</c>
</row>
<row r="4" spans="1:1" x14ac:dyDescent="0.25">
<c r="A4">
<v>4</v>
</c>
</row>
<row r="5" spans="1:1" x14ac:dyDescent="0.25">
<c r="A5">
<v>5</v>
</c>
</row>
</sheetData>
<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3" />
</worksheet>
若要使用此方法,请执行以下操作:
\xl\worksheets
\xl\worksheets
sheetX.xml
文件,使用H 224H 125
打开excel文件,以查看只有4个值存在H 226G 227
https://stackoverflow.com/questions/58761501
复制相似问题