这部分主要用Iterator
1、做一个数据提供的类
package dao;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.testng.annotations.DataProvider;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* @author wangyan
* @date 2019-02-20 下午 04:55
*/
public class DataProviderSet_xlsx {
public static String excelName="testdata";
@DataProvider(name="mapDataProvider")
public static Iterator<Object[]> mapDataProvider() {
List<Object[]> datas=new ArrayList<>();
InputStream in=null;
DataFormatter dataFormatter=new DataFormatter();
try {
in= DataProviderSet_xlsx.class.getClassLoader().getResourceAsStream(excelName+".xlsx");
XSSFWorkbook workbook=new XSSFWorkbook(in);
Sheet sheet = workbook.getSheet("test");
Row header=sheet.getRow(0);
Iterator<Row> rows=sheet.rowIterator();
boolean isFirstRow=true;
while (rows.hasNext()){
Row row=rows.next();
if(isFirstRow){
isFirstRow=false;
continue;
}
HashMap<String,String> rowMap=new HashMap<>();
Iterator<Cell> cells=row.cellIterator();
while (cells.hasNext()){
Cell cell=cells.next();
rowMap.put(dataFormatter.formatCellValue(header.getCell(cell.getColumnIndex())),
dataFormatter.formatCellValue(cell));
}
datas.add(new Object[]{rowMap});
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(in !=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return datas.iterator();
}
}
2、测试类,获取数据提供
package configSelenium.Assert;
import dao.DataProviderSet_xlsx;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.*;
/**
* @author wangyan
* @date 2019-01-18 下午 04:55
*
*/
public class sql {
@Test(dataProvider = "mapDataProvider",dataProviderClass = DataProviderSet_xlsx.class)
public void testMapDataProviderFromExcel(HashMap<String,String> map){
Set<Map.Entry<String,String>> sets=map.entrySet();
Iterator<Map.Entry<String,String>> iterEntry=sets.iterator();
while (iterEntry.hasNext()){
Map.Entry<String,String> entry=iterEntry.next();
System.out.println(entry.getKey()+"->"+entry.getValue());
}
}
}