testNG数据驱动测试(一):java利用opi创建excel并写入数据
maven的pom.xml文件,写入下面两条:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
下面都是用的XSSF开头的类,文件后缀为“.xlsx”
(HSSF开头的类对应文件后缀为“.xls”)
注意:由于整体架构需要,所以每个项都建了一个集合,这个根据实际需要也可以建一个类的集合。
// 定义表头
String[] title = {"实际结果", "预期结果", "描述", "测试结果"};
// 定义实际结果集
// List<Object[]> data = new ArrayList<>();
// data.add(new Object[]{"大王", "小王", "判断相等"});
// data.add(new Object[]{"张三", "李四", "测试项目人名称"});
List<String> actuallist = new ArrayList<>();
List<String> exceptlist = new ArrayList<>();
List<String> description = new ArrayList<>();
actuallist.add("大王");
actuallist.add("12");
actuallist.add("89sasd");
exceptlist.add("小王");
exceptlist.add("12");
exceptlist.add("423asd");
description.add("case1");
description.add("case2");
description.add("case3");
//创建excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//创建工作表sheet
XSSFSheet sheet = workbook.createSheet();
//创建第一行
XSSFRow row = sheet.createRow(0);
XSSFCell cell = null;
//插入第一行的表头
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
for (int i = 1; i <actuallist.size()+1; i++) {
XSSFRow nrow = sheet.createRow(i);
XSSFCell ncell = nrow.createCell(0);
ncell.setCellValue(actuallist.get(i-1));
ncell=nrow.createCell(1);
ncell.setCellValue(exceptlist.get(i-1));
ncell=nrow.createCell(2);
ncell.setCellValue(description.get(i-1));
}
//创建excel文件
//这里的路径就是项目下的resources文件夹里面
File file=new File("./src/main/resources/testdata.xlsx");
try {
System.out.println(file.getCanonicalPath());
file.createNewFile();
//将excel写入
FileOutputStream stream= FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
以上可以先写在一个main方法测试一下,然后根据业务需要来规划即可。
喜欢请点个赞吧!(@_@)