前一篇的代码中我们已经在登录的用户、密码和验证码等地方使用了数据驱动,这一篇主要讲解数据驱动的具体实现:
目录结构如下 :
1、在maven的pom.xml文件中引入poi的jar包
2、我们在框架的第一层framework包下面建一个Excel.java类,里面实现Excel单元格的读写内容如下 :
package framework;
import org.apache.poi.ss.formula.SheetNameFormatter;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import framework.Log;
public class Excel {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
private static String path;
public static void setExcelFile(String path,String SheetName)throws Exception{
FileInputStream ExcelFile;
try{
ExcelFile=new FileInputStream(path);
Log.info("实例化Excel文件的FileInputStream");
ExcelWBook=new XSSFWorkbook(ExcelFile);
Log.info("实例化Excel文件的XSSFWorkbook");
ExcelWSheet=ExcelWBook.getSheet(SheetName);
Log.info("实例化XSSFSheet对象,指定Excel文件中的sheet名称,后续用于sheet中行、列和单元格的操作");
}catch(Exception e){
throw(e);
}
}
//读取Excel文件指定单元格函数
public static String getCellData(int RowNum,int ColNum){
try{
Cell=ExcelWSheet.getRow(RowNum).getCell(ColNum);
Log.info("通过函数参数指定单元格行号和列号,获取指定单元格对象");
//三元表达式:如果单元格中为字符串型使用getStringCellValue()获取单元格中内容;如果为数字型使用getNumericCellValue()获取单元格中内容,获取的double型必须转化为String型;
String CellData=Cell.getCellTypeEnum()== CellType.STRING?Cell.getStringCellValue()+"":String.valueOf(Math.round(Cell.getNumericCellValue()));
Log.info("获取单元格的内容,有字符型和数字型两种");
return CellData;
}catch(Exception e){
return "";
}
}
//写入单元格这个方法有问题;
public static void setCellData(int RowNum, int ColNum, String Result)throws Exception{
try{
Row=ExcelWSheet.getRow(RowNum);
Log.info("获取Excel文件中的行对象");
Cell= Row.getCell(0000); //原代码 Cell=Row.getCell(ColNum,Row.RETURN_BLANK_AS_NULL);
if(Cell==null){
Log.info("当单元格对象是Null的时候,则创建单元格");
Cell=Row.createCell(ColNum);
Cell.setCellValue(Result);
Log.info("创建单元格后可以调用单元格对象的setCellValue方法设定单元格的值");
}
else{
Cell.setCellValue(Result);
Log.info("单元格中有内容,则可以直接调用单元格对象的setCellValue方法设定单元格的值");
}
FileOutputStream fileOut=new FileOutputStream(path);
ExcelWBook.write(fileOut);
Log.info("将内容写入Excel中");
fileOut.flush();
fileOut.close();
}catch(Exception e){
throw(e);
}
}
}
上面代码中往Excel中写入的操作还有问题没有完全实现,后续会进行修改完善。注意2003版的Excel和2007版的Excel创建对象的类不同:(最好利用正则表达式)
// HSSFWorkbook 2003的excel .xls,XSSFWorkbook导入2007的excel .xlsx
HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(new File(file)));
XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(new File(file))));
3、在第二层框架中需要使用Excel表格中的数据时,先导入import framework.Excel;然后通过行和列取到Excel表格中的值:
type(username_inputBox,excel.getCellData(1,0));