Selenium框架搭建—读excel文档中的数据

要想使用java代码调用excle中的数据,需要先导入POI jar包
Apache POI的使用:
Apache POI: Apache POI是Apache软件基金会的开放源码函式库,POI提供API给 Java 程序对Microsoft Office格式档案读和写的功能。
1、jar包下载地址:

2、下载后导入到项目中
首先点击项目右键-bulid path-Add Libraries,选择User Library
然后点击User Libraries

最后,新建一个文件夹并导入下载的jar包
3、新建一个class,复制已经封装好的代码到该class中
public static Object[][] getTestDataByExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath + "\\" + fileName);
System.out.println("file is :" + file);
FileInputStream inputstream = new FileInputStream(file);
Workbook workbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if (fileExtensionName.equals(".xlsx")) {
workbook = new XSSFWorkbook(inputstream);
} else if (fileExtensionName.equals(".xls")) {
workbook = new HSSFWorkbook(inputstream);
} else {
throw new IOException("wrong fileName");
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
List<Object[]> records = new ArrayList<Object[]>();
for (int i = 1; i < rowCount + 1; i++) {
Row row = sheet.getRow(i);
String fields[] = new String[row.getLastCellNum()];
for (int j = 0; j < row.getLastCellNum(); j++) {
if (row.getCell(j).getCellType() == 0) {
fields[j] = row.getCell(j).getNumericCellValue() + "";
} else {
fields[j] = row.getCell(j).getStringCellValue();
}
}
records.add(fields);
}
Object[][] results = new Object[records.size()][];
for (int x = 0; x < records.size(); x++) {
results[x] = records.get(x);
}
inputstream.close();
workbook.close();
return results;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值