pom.xm 依赖:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Excel 读取类:通过迭代器实现,这样比较方便封装,实现 Excel 读取类型的多态性;这里用的是 Map 实现;
public class ExcelIterator implements Iterator<Object[]> {
private Workbook book = null;
private Sheet sheet = null;
private int rowNum = 0;
private int curRowNo = 0;
private int columnNum = 0;
private String[] columnName;
private int singleline = 0;
public ExcelIterator(String filename, String testMethodname) {
try {
FileInputStream fs = new FileInputStream(filename);
this.book = Workbook.getWorkbook(fs);
this.sheet = book.getSheet(testMethodname);
this.rowNum = sheet.getRows();
Cell[] c = sheet.getRow(0);
this.columnNum = c.length;
columnName = new String[c.length];
for (int i = 0; i < c.length; i++) {
columnName[i] = c[i].getContents().toString();
}
if (this.singleline > 0) {
this.curRowNo = this.singleline;
} else {
this.curRowNo++;
}
} catch (FileNotFoundException e) {
System.out.println("文件IO异常");
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean hasNext() {
if (this.rowNum == 0 || this.curRowNo >= this.rowNum) {
book.close();
return false;
}
if (this.singleline > 0 && this.curRowNo > this.singleline) {
book.close();
return false;
}
return true;
}
@Override
public Object[] next() {
Cell[] c = sheet.getRow(this.curRowNo);
Map<String, Object> s = new LinkedHashMap<String, Object>();
for (int i = 0; i < this.columnNum; i++) {
String data = c[i].getContents().toString();
s.put(this.columnName[i], data);
}
this.curRowNo++;
return new Object[] { s };
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
读取 Excle 用例示例:
public class TestDriverData {
@Test(dataProvider = "test_selenium1")
public void f(Map<String, String> data) {
System.out.println("用例标题:" + data.get("comment"));
}
@DataProvider(name = "test_selenium1")
public Iterator<Object[]> dataProvider() {
return new ExcelIterator("D:\\data\\ErShouFangWebDetailTest.xls", "testEsfWebDetail");
}
}
Excel 展示:
Excel 读取执行用例结果: