【问题标题】:Read data from Excel file in Selenium Java在 Selenium Java 中从 Excel 文件中读取数据
【发布时间】:2013-10-24 06:49:55
【问题描述】:

我正在尝试从 excel 表中读取数据以自动化我的测试(使用多个登录凭据)。我正在使用我在网上找到的实用程序。但它没有成功运行。

这是实用程序

    package google;

    import java.io.File;
    import java.io.IOException;
    import java.util.Hashtable; 

    import jxl.Cell;
    import jxl.Sheet;
    import jxl.Workbook;
    import jxl.read.biff.BiffException;

    public class class2 {

    static Sheet wrksheet;
    static Workbook wrkbook =null;
    static Hashtable dict= new Hashtable();
     //Create a Constructor
    public class2(String ExcelSheetPath) throws BiffException, IOException
    {
    //Initialize
    wrkbook = Workbook.getWorkbook(new File(ExcelSheetPath));
    //For Demo purpose the excel sheet path is hardcoded, but not recommended :)
    wrksheet = wrkbook.getSheet("Sheet1");
    }

    //Returns the Number of Rows
    public static int RowCount()
    {
    return wrksheet.getRows();
   `enter code here` }

    //Returns the Cell value by taking row and Column values as argument
    public static String ReadCell(int column,int row)
    {
    return wrksheet.getCell(column,row).getContents();
    }

    //Create Column Dictionary to hold all the Column Names
    public static void ColumnDictionary()
    {`enter code here`
    //Iterate through all the columns in the Excel sheet and store the value       
    for(int col=0; col <= wrksheet.getColumns();col++)
    {
    dict.put(ReadCell(col,0), col);
    }
    }

    //Read Column Names
    public static int GetCell(String colName)
    {
    try {
    int value;
    value = ((Integer) dict.get(colName)).intValue();
    return value;
    } catch (NullPointerException e) {
    return (0);

    }
    }

    }

以下是调用此实用程序的类。

package google;

import java.io.IOException;

import jxl.read.biff.BiffException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import google.class2;

public class class3 {

//Global initialization of Variables
static class2 xlsUtil;
WebDriver driver = new InternetExplorerDriver();

//Constructor to initialze Excel for Data source
public class3() throws BiffException, IOException
{
//Let's assume we have only one Excel File which holds all Testcases. Demo !!!
 xlsUtil = new class2("C:/Users/admin/workspace/login.xls");
 //Load the Excel Sheet Col in to Dictionary for Further use in our Test cases.
 xlsUtil.ColumnDictionary();
 }

@BeforeTest
public void EnvironmentalSetup()
{
   System.setProperty("webdriver.chrome.driver",
 "C:/Users/admin/Downloads/chromedriver.exe");
  WebDriver driver = new ChromeDriver();
   driver.get("http://192.168.1.20/dental/userlogin");
}

@Test

public void GmailLoginPage() throws InterruptedException {

//Create a for loop.. for iterate through our Excel sheet for all the test cases.
for(int rowCnt = 1;rowCnt <= xlsUtil.RowCount();rowCnt++)
{

//Enter User Name by reading data from Excel
WebElement userName = driver.findElement(By.name("UserName"));
userName.clear();
userName.sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("EmailUserName"), rowCnt));

//Enter Password
WebElement password = driver.findElement(By.name("Password"));
password.clear();
password.sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("Emailpassword"), rowCnt));

//Click on the Sign In Button
// WebElement signin = driver.findElement(By.name("signIn"));
password.submit();

//Sleep for some time,so that we can see things in action @ Screen :)
Thread.sleep(2000);
}
}

}

但是当我运行 dis cass 时,它显示“无法实例化 google.class3 我不明白这里的错误。 请帮我成功运行这段代码。

【问题讨论】:

  • 仅供参考:我建议将 Apache POI 用于任何具有 MS Office 格式的操作。它是一个非常稳定、成熟且广泛使用的库。
  • 粗略猜测,但不要在构造函数中使用 throws 子句,而是在构造函数中使用 try catch 块并检查它。可能是原因
  • 代码可以在这里找到https://docs.google.com/document/d/1p9E_Ob9HevUVdOXOOylLMgqL7J_KTxygHj_f8PJr4lg/edit
  • balaji krishnan,我试过这样做,但结果相同。 :(
  • 考虑 popfalushi 的提示。几年来,我们一直在使用 ApachePOI 进行基于 Excel 的测试,它(我引用):“非常稳定、成熟的库”

标签: java eclipse excel selenium


【解决方案1】:
FileInputStream file = newFileInputStream(newFile("C:/Users/admin/workspace/login.xls"));

    //Get the workbook instance for XLS file 
    HSSFWorkbook workbook = new HSSFWorkbook(file);

    //Get first sheet from the workbook
    HSSFSheet sheet = workbook.getSheetAt(0);

    //Iterate through each rows from first sheet
    Iterator<Row> rowIterator = sheet.iterator();

    while(rowIterator.hasNext()) {

        Row row = rowIterator.next();

        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {        

            Cell cell = cellIterator.next();
            if(cell.getColumnIndex() == 0){
                     driver.findElement(By.name("UserName")).sendKeys(cell.getStringCellValue());
            }
            else
                driver.findElement(By.name("Password")).sendKeys(cell.getStringCellValue());
        }

【讨论】:

    【解决方案2】:
    public String getExcelData(String sheetName , int rowNum , int colNum) throws InvalidFormatException, IOException{
          FileInputStream fis = new FileInputStream(filePath);
          Workbook wb = WorkbookFactory.create(fis);
          Sheet sh = wb.getSheet(sheetName);    
          Row row = sh.getRow(rowNum);
          String data = row.getCell(colNum).getStringCellValue();
          return data;
    }
    
    public int getRowCount(String sheetName) throws InvalidFormatException, IOException{    
          FileInputStream fis = new FileInputStream(filePath);
          Workbook wb = WorkbookFactory.create(fis);
          Sheet sh = wb.getSheet(sheetName);
          int rowCount = sh.getLastRowNum()+1;
          return rowCount;
    }
    
    public void setExcelData(String sheetName,int rowNum,int colNum,String data) throws InvalidFormatException, IOException{
          FileInputStream fis = new FileInputStream(filePath);
          Workbook wb = WorkbookFactory.create(fis);
          Sheet sh = wb.getSheet(sheetName);
          Row row = sh.getRow(rowNum);
          Cell cel = row.createCell(colNum);
          cel.setCellType(cel.CELL_TYPE_STRING);
          cel.setCellValue(data);
          FileOutputStream fos = new FileOutputStream(filePath);
          wb.write(fos);      
    }
    
    public int getcellCount(String sheetName,int rowNum) throws InvalidFormatException, IOException{
          FileInputStream fis = new FileInputStream(filePath);
          Workbook wb = WorkbookFactory.create(fis);
          Sheet sh = wb.getSheet(sheetName);    
          Row row = sh.getRow(rowNum);
         return row.getLastCellNum();     
    }
    

    【讨论】:

      【解决方案3】:
      public class ExcelLIb {
      
      public static String filePath;
      
      public String getExcelData(String sheetName , String testID , String columnHeader) throws InvalidFormatException, IOException{
      
          String userDir = System.getProperty("user.dir");
          filePath = userDir+"\\testdata\\Test_Data.xlsx";
          String data = null;
          FileInputStream fis = new FileInputStream(filePath);
          Workbook wb = WorkbookFactory.create(fis);
          Sheet sh = wb.getSheet(sheetName);
          int rowcount =getRowCount(sheetName);
      
          for(int r=0 ; r<rowcount; r++){
              Row row = sh.getRow(r);
              if(row.getCell(0).getStringCellValue().toLowerCase().equals(testID.toLowerCase())){
              int col =  row.getLastCellNum();
                  for(int c=0; c<col ; c++){
                    if(row.getCell(c).getStringCellValue().toLowerCase().equals(columnHeader.toLowerCase())){
                        row = sh.getRow(r+1);
                        data = row.getCell(c).getStringCellValue();
                        break;
                        }
                    }
                 }
              }
          return data;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多