Tuesday, April 14, 2015

Read data from excel file-Sample Java code by using jxl.jar

Here i am sharing the sample java code for reading the data from cell values of MS Excel.

Prerequisite:

1.  Download jxl.jar, and add that your java build path. 
2.  Download testng.jar and add that your java build path. (not necessary)
3. Prepare excel sheet with your data. 

Below program is for login to the gmail.com by using username and password given in the sheet.

Here i am displaying sample format of excel sheet. 



Code:
import java.io.FileInputStream;

import jxl.Sheet;
import jxl.Workbook;

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

public class Data {
    private WebDriver driver;

    @BeforeClass
    public void setup()
    {
        driver = new FirefoxDriver();
    }

    @Test(description = "Read Gmail account")
    public void Login() throws Exception
    {
        FileInputStream fi = new FileInputStream("E:\\testemail.xls");
        Workbook w = Workbook.getWorkbook(fi);
        Sheet s = w.getSheet(0);
        System.out.println(s.getRows());
        driver.get("http://www.gmail.com");
        try {
            for (int i = 1; i < s.getRows(); i++) {
                // Read data from excel sheet
                String s1 = s.getCell(0, i).getContents();
                String s2 = s.getCell(1, i).getContents();
                driver.findElement(By.name("Email")).sendKeys(s1);
                driver.findElement(By.name("Passwd")).sendKeys(s2);
                driver.findElement(By.name("signIn")).click();
                driver.findElement(By.name("signout")).click();

            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @AfterClass
    public void teardown()
    {
        driver.quit();
    }

}

 

 

No comments:

Post a Comment