从Excelsheet读取数据

时间:2019-07-15 09:03:55

标签: java apache selenium

从Excel工作表(java)读取数据

我已经创建了使用Java来从excel表格中读取数据到我的登录网页(用户名和密码)的自动化工具。所以我想知道为什么这段代码在eclipse中不能正常运行?

我已经使用了TestNg框架,并尝试使用dataprovider。它显示此错误“ java.lang.NoClassDefFoundError:org / apache / commons / collections4 / ListValuedMap”

1.Dataprovidertest类

private String filePath = "C:\\Users\\samudil\\eclipse-workspace\\ZharaProject\\src\\Excelsheet\\TestData.xlsx";
private String sheetName = "Sheet1";

 @Test(dataProvider = "excelData")
        public void read(String username, String password) throws InterruptedException {

            //handle popup window
            Set<String> windowId = driver.getWindowHandles();    // get  window id of current window
             Iterator<String> itererator = windowId.iterator();   

             String mainWinID = itererator.next();
             String  newAdwinID = itererator.next();

             driver.switchTo().window(newAdwinID);
             System.out.println(driver.getTitle());
             Thread.sleep(3000);

             driver.findElement(By.xpath("//input[@id='j_username']")).sendKeys(username);
             driver.findElement(By.xpath("//*[@id=\"j_password\"]")).sendKeys(password);
             driver.findElement(By.xpath(".//*[@id='account']/a")).click();


        }

        @DataProvider(name="excelData")
        public Object[][] readExcel() throws InvalidFormatException, IOException {
            return TestUtil.readExcel(filePath, sheetName);
        }  

2.TestUtil类

public class TestUtil {

    public static Object[][] readExcel(String filePath, String sheetName) throws InvalidFormatException, IOException {
        FileInputStream file= new FileInputStream(filePath);
        XSSFWorkbook wb = new XSSFWorkbook(file);
        XSSFSheet sheet = wb.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        int column = sheet.getRow(0).getLastCellNum();
        Object[][] data = new Object[rowCount][column];
        for (int i = 1; i <= rowCount; i++) {
            XSSFRow row = sheet.getRow(i);
            for (int j = 0; j < column; j++) {
                XSSFCell cell = row.getCell(j);
                DataFormatter formatter = new DataFormatter();
                String val = formatter.formatCellValue(cell);
                data[i - 1][j] = val;
            }
        }

        return data;
    }

}

2 个答案:

答案 0 :(得分:0)

非常清楚。这表示找不到您所使用的类的类定义。这是一个一般性异常,如果您错过依赖项,任何时候都可能发生。

请添加

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4
 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version> 
</dependency>

如果您使用的是maven,或者直接添加jar文件。 您可以从这里获取罐子:Maven Link

答案 1 :(得分:0)

假设您已经添加了所有必需的依赖项(根据您的评论)。 请尝试以下步骤,其中之一可能会有所帮助。

  1. 重启日食
  2. 清理项目(右键单击项目-> Run As-> Maven Clean)
  3. 更新项目(右键单击该项目-> Maven->更新项目->选择您的项目->确定)

如果执行这些步骤后仍然遇到此问题,则可能有其他问题。