首页 > 代码库 > selenium代码练习(ApachePOI)
selenium代码练习(ApachePOI)
可以读取excel中任意一行的数据
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ApachePoiDemo {
// @Test(dataProvider="dataDriven")
// public void testAdd(double a,double b,double c){
// Assert.assertEquals(a+b, c);
//
// }
//
@DataProvider(name="dataDriven")
public Object[][] generateData() throws IOException
{
return getTestData("data/data3.xlsx");
}
public static Object[][] getTestData(String filelocation) throws IOException{
//读取文件
File file=new File(filelocation);
FileInputStream fis=new FileInputStream(file);
//读取工作簿
XSSFWorkbook workbook=new XSSFWorkbook(fis);
//访问sheet页
XSSFSheet sheet=workbook.getSheetAt(0);
//获取表格的列数
int colCount=sheet.getRow(0).getPhysicalNumberOfCells();
//获取表格的行数
int rowCount=sheet.getPhysicalNumberOfRows();
//创建二维数组
Object[][] ret=new Object[rowCount-1][colCount];
//读取表格数据并赋值给二维数组
for(int i=0;i<rowCount-1;i++){
for(int j=0;j<colCount;j++){
//获取单元格数据
Cell cell=sheet.getRow(i+1).getCell(j);
switch(cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:
ret[i][j]=cell.getNumericCellValue();break;
case Cell.CELL_TYPE_STRING:
ret[i][j]=cell.getStringCellValue();break;
default:
System.out.println("单元格类型有误");
}
}
}
//关闭文件流
fis.close();
return ret;
}
}
selenium代码练习(ApachePOI)