我正在使用 Selenium 2 并设置了一个 LoginTest.java 文件,该文件从数据驱动的 excel 文件中读取。我读入用户名和密码并在登录页面上运行它。它实际上运行良好。数据如下所示:
用户1 pw1
用户2 pw2
user3 pw3
user4 pw4
问题是这样的:如果我修改 Excel 文件并将参数数量更改为如下所示:
用户1 pw1
用户2密码2
并运行相同的脚本,ReadExcel
类文件返回错误消息:
"There is no support for this type of cell".
我认为发生的情况是,第 3 行和第 4 行曾经在其单元格(user3 pw3 和 user4 pw4)中包含数据,但现在它们不包含数据......所以有一些不同的东西关于我的 ExcelRead()
类无法捕获并忽略的那些以前使用过的单元格。我敢打赌,该单元格现在是“空”,而以前不是,反之亦然。以前保存过数据的单元格与从未保存过数据的单元格有些不同。
(我在互联网上找到了 ExcelRead
并正在使用它。我自己并不是从头开始创建它。它似乎可以很好地读取 xcel 文件,除了这个“问题”)。
感谢您的帮助。
public class ExcelRead {
public Object[][] main( String[] args) throws Exception{
File excel = new File(args[0]);
FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet(args[1]);
int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum];
for (int i = 0 ; i < rowNum ; i++) {
HSSFRow row = ws.getRow(i);
for (int j = 0 ; j < colNum ; j++) {
HSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[i][j] = value ;
//System.out.println("the value is " + value);
}
}
return data;
}
public static String cellToString(HSSFCell cell) {
int type;
Object result;
type = cell.getCellType();
switch (type) {
case 0: // numeric value in Excel
result = cell.getNumericCellValue();
break;
case 1: // String Value in Excel
result = cell.getStringCellValue();
break;
default:
throw new RuntimeException("There is no support for this type of cell");
}
return result.toString();
}
最佳答案
您下载的代码使用 Java Apache POI 库来读取 Excel 文件。如果您仔细阅读代码,您会发现 cellToString()
方法并不处理所有类型的单元格类型 - 它仅查找数字和字符串单元格,并抛出您在其他情况下看到的异常。
从行中删除单元格值后,单元格值现在为空,并且单元格类型为 CELL_TYPE_BLANK
。
您需要扩展 cellToString()
方法中的 switch
语句来处理其他单元格类型,例如 Cell.CELL_TYPE_BLANK
、Cell.CELL_TYPE_BOOLEAN
等。
请参阅Apache POI documentation在 Cell
界面上查看不同的细胞类型以及如何处理每种类型。
public static String cellToString(HSSFCell cell) {
int type;
Object result;
type = cell.getCellType();
switch (type) {
case Cell.CELL_TYPE_NUMERIC: // numeric value in Excel
case Cell.CELL_TYPE_FORMULA: // precomputed value based on formula
result = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING: // String Value in Excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
result = "";
case Cell.CELL_TYPE_BOOLEAN: //boolean value
result: cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_ERROR:
default:
throw new RuntimeException("There is no support for this type of cell");
}
return result.toString();
}
关于java - 使用 Apache POI 从 Excel 文件读取单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20336778/