Sunday, 23 November 2014

How to read data from excel in selenium

Read data in excel
First,
download JXL or POI jar file and build it to your project
http://download.cnet.com/JExcelApi/3000-2077_4-75912876.html
Second,
We Should have access to workbook, sheet which we want to read as workbook contains multiple sheets and if you want to read a particular cell we need location of a Cell.


FileInputStream fis = new FileInputStream(
"D:\\SELENIUM\\EXCEL\\login.xls");
Workbook wb = Workbook.getWorkbook(fis);


Next to access sheet


Sheet s = wb.getSheet(0); // this is to get the access to Sheet0.


To get the cell contents as below:
 
Cell c = s.getCell(icol, irow);
String exceldata = c.getContents();


For reading more than one properties


if (sprop.startsWith("//")) {
driver.findElement(By.xpath(sprop)).sendKeys(sval);
} else {
driver.findElement(By.id(sprop)).sendKeys(sval);




For reading from excel
textBox(ExcelRead(2, i), ExcelRead(3, i));


exceldata1


Prog is :
//how to read data from excel in selenium
package com.Test;


import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


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


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;


public class ReadDataExcel {
WebDriver driver;


@Test
public void text() throws BiffException, IOException {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.rightstart.com/customer/account/login");
for (int i = 1; i < 3; i++) {
textBox(ExcelRead(2, i), ExcelRead(3, i));
}
}


public String ExcelRead(int icol, int irow) throws BiffException,
IOException {
FileInputStream fis = new FileInputStream(
"D:\\SELENIUM\\EXCEL\\login.xls");
Workbook wb = Workbook.getWorkbook(fis);
Sheet s = wb.getSheet(0);
Cell c = s.getCell(icol, irow);
String exceldata = c.getContents();
return exceldata;
}


public void textBox(String sprop, String sval) {
if (sprop.startsWith("//")) {
driver.findElement(By.xpath(sprop)).sendKeys(sval);
} else {
driver.findElement(By.id(sprop)).sendKeys(sval);
}
}
}


OUTPUT IS






rigclickreaddata

No comments:

Post a Comment