我这里有一个代码片段:
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
public static void setExcelFile(String Path) throws Exception {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
}
public static String getCellData(int RowNum, int ColNum, String SheetName ) throws Exception{
ExcelWSheet = ExcelWBook.getSheet(SheetName);
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
}
public static int getRowCount(String SheetName){
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number=ExcelWSheet.getLastRowNum()+1;
return number;
}
public static int getRowContains(String sTestCaseName, int colNum,String SheetName) throws Exception{
int i;
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int rowCount = ExcelUtils.getRowCount(SheetName);
for (i=0 ; i<rowCount; i++){
if (ExcelUtils.getCellData(i,colNum,SheetName).equalsIgnoreCase(sTestCaseName)){
break;
}
}
return i;
}
// this is the method that I have trouble understanding, and its purpose
public static int getTestStepsCount(String SheetName, String sTestCaseID, int iTestCaseStart) throws Exception{
for(int i=iTestCaseStart;i<=ExcelUtils.getRowCount(SheetName);i++){
if(!sTestCaseID.equals(ExcelUtils.getCellData(i, Constants.Col_TestCaseID, SheetName))){
int number = i;
return number;
}
}
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number=ExcelWSheet.getLastRowNum()+1;
return number;
}
}
我理解代码中的所有方法(除了一个),例如: getCellData() 返回特定行&列中的数据。 getRowCount() 返回工作表中的行数。 getRowContains() 返回某条数据所在的行。
我不理解的方法是最后一个方法“getTestStepsCount”。我试过一遍又一遍地阅读它,但我就是不明白。看起来很像 getRowCount 方法,但同时又不是。
请有经验的代码阅读者帮助我理解它吗?
最佳答案
您的方法只是检查指定工作表的指定列中的每一行。
一步一步:
方法参数:
- String SheetName => 进行验证的工作表的名称
- String sTestCaseID => 你要查找的字符串
- int iTestCaseStart => 用作搜索偏移量的行数
方法步骤:
- for循环进行查找,找到则返回结果
- 如果循环没有结果,则返回另一个值
步骤 1 的详细信息:
for(int i=iTestCaseStart;i<=ExcelUtils.getRowCount(SheetName);i++){
if(!sTestCaseID.equals(ExcelUtils.getCellData(i, Constants.Col_TestCaseID, SheetName))){
int number = i;
return number;
}
}
此处 for
循环在您的偏移量 iTestCaseStart
和工作表的行数之间迭代。
对于此循环中的每一行,它正在检查第 i
行和 Constants.Col_TestCaseID
列的单元格内的数据是否与 的值不同sTestCaseID
.
- 如果它们不同,该方法将得到行的索引(即
i
的值)作为结果。 - 如果不是,继续迭代
如果在最后一行之前没有发现不同的值,则循环结束,然后执行第 2 步。
第 2 步的详细信息:
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number=ExcelWSheet.getLastRowNum()+1;
return number;
如果进入第2步,该方法将返回最后一行的索引+1
补充意见
在这段代码中可以做很多改进...
关于java - 这个excel方法在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418795/