[英]How to get the row index of last non-empty cell for a specific column name(passed as an argument) from an excel sheet using java?
該模塊的摘要,它以書名,圖紙名和列名作為參數,並期望該模塊返回所需的行索引。
public int getExcelData(String WBookName, String sheetName, String columnName) {
int colNum = -1;
int rowIndex = -1;
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/"+WBookName+".xls");
try {
excelWBook = new XSSFWorkbook(inputStream);
Log.info(WBookName+"Excel File loaded Successfully");
} catch (IOException e) {
Log.fatal("Unable to load"+WBookName+" Excel File");
e.printStackTrace();
}
excelWSheet = excelWBook.getSheet(sheetName);
row = excelWSheet.getRow(0);
for(int i=0; i<row.getLastCellNum();i++) {
if(row.getCell(i).getStringCellValue().trim().equals(columnName)){
colNum = i;
}
}
{
//code for getting last non-empty row for a columnName (Possible using Iterator?)
}
return rowIndex;
由於Apache POI具有方法Sheet#getLastRowNum()
,因此我將使用從excelWSheet.getLastRowNum()
到0
的for循環,然后向每一行詢問是否存在值。
代碼將是這樣的 (您應該自己嘗試,我現在只是“在瀏覽器中編程”)如下:
for (int rowNum = excelWSheet.getLastRowNum(); rowNum >= 0; rowNum--) {
final Row row = excelWSheet.getRow(rowNum);
if (row != null && row.getCell(colNum) != null) {
rowIndex = rowNum;
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.