Wednesday, May 16, 2012

Reading and writing data in excel sheet using Selenium web driver 2.0

Reading and writing data in excel sheet is quite easy. Here is the simple example to read and write data using selenium web driver 2.0. Import jxl jar file and then run the script

Reading data from excel:


 public String[][] getXLData(String location, String sheetname)
       {
               Workbook w = null;
               try {
                       w = Workbook.getWorkbook(new File(location));
               } catch (BiffException e) {
                       e.printStackTrace();
               } catch (IOException e) {
                       e.printStackTrace();
               }
               Sheet s = w.getSheet(sheetname);
               String a[][] = new String[10][10];
               try
               {
               for (int j=0;j<s.getColumns();j++)
               {
                       for (int i=0;i<s.getRows();i++)
                       {
                               a[j][i] = s.getCell(j, i).getContents();
                               System.out.println(j+" and "+i+" "+a[j][i]);
                       }
               }

               }
               catch(Exception e)
               {
                       e.printStackTrace();
               }
               return a;
       }

Writing data to excel:

A simple example to write the title of the page in the excel sheet


public class google {
private WebDriver driver;

@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void test() throws Exception {
driver.get("http://www.google.co.in/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Testing");
driver.findElement(By.id("gbqfq")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("Software testing - Wikipedia, the free encyclopedia")).click();
String s = driver.getTitle();
writereport(s);

}

@After
public void tearDown() throws Exception {
driver.quit();
}



public void writereport(String text) 
       { 
        try
        {
       FileOutputStream f = new FileOutputStream("c:\\Test\\output.xls",true);
       WritableWorkbook book = Workbook.createWorkbook(f); 
       WritableSheet sheet = book.createSheet("output", 0);
       Label l = new Label(0, 0, text);
       sheet.addCell(l);
       book.write(); 
       book.close(); 
        }
        catch (Exception e)
        {
        e.printStackTrace();
        }
        }



42 comments:

  1. while using this code showing error, for removing error which package I have have to import.
    Please define the following code in brief....


    FileOutputStream f = new FileOutputStream("c:\\Test\\output.xls",true);
    WritableWorkbook book = Workbook.createWorkbook(f);
    WritableSheet sheet = book.createSheet("output", 0);
    Label l = new .Label(0, 0, text);

    Thanks.............

    ReplyDelete
  2. Hi Rahul,

    Import JXL jar file.... (Writable)

    can you share the error message here?

    ReplyDelete
  3. there is an error in
    Label l = new .Label(0, 0, text);
    it saying "Syntax error on token "new", invalid Expression".

    thanks

    ReplyDelete
  4. Its working fine

    import jxl.write.Label and use Label l = new Label(0, 0, text);

    Thanks

    ReplyDelete
  5. i m trying to implement the same code as Rahul did,,even m getting tha same errror...i imported jxl file ..but getting erroe as syntax error...at this point
    Label l = new Label(0, 0, text);
    sheet.addCell(l);

    ReplyDelete
  6. Its working. Use either

    1) import jxl.write.Label;

    or

    2) jxl.write.Label l = new Label(0, 0, text);


    Thanks

    ReplyDelete
  7. I have used the same code to get Text of "Software testing" on wiki page
    used below code
    =====
    String s=driver.findElement(By.xpath("//span[text()=\"Software testing\"]")).getText();
    ======================
    By default it is writing : Testing-google search

    Though,
    System.out.println("printin l="+l.getContents()); is printing "Software Testing"

    ReplyDelete
  8. Hi Ramesh,

    Use Thread.sleep(in milliseconds); before writing the text

    Thanks,
    Arun

    ReplyDelete
  9. i used above code for write title in excel sheet..but there write junk data...how i solve this problem??
    do i need to do entry as a column header in file before through selenium webdriver.

    ReplyDelete
  10. Hi Ankit,

    No need to put column header in file. For verifying, try to print the output in the application using System.out.println"(Title is "+s);

    ReplyDelete
  11. Hello ,
    My above problem now solved ...
    My new problem is-
    I want to write data in excel sheet through twoo functions one-url,second-text.
    i used above code..pls check and give me solution.How i write data using second function---writeurl(text)??

    for(int i=1;i<Number;i++)
    {
    String url=wDriver.findElement(By.xpath("//*[@id='videogallery']/a[position() = " + i +"]")).getAttribute("href");
    String tt=wDriver.findElement(By.xpath("//*[@id='videogallery']/a[position() = " + i +"]")).getText();
    writeurl(url);
    writeurl(text);
    }

    }

    @AfterClass
    public void End()throws Exception{
    wDriver.quit();
    }

    public void writeurl(String url)
    {
    try
    {
    File exlFile = new File("C:/Test/output.xls");
    WritableWorkbook writableWorkbook = Workbook.createWorkbook(exlFile);
    WritableSheet writableSheet = writableWorkbook.createSheet("Sheet1", 0);
    Label label = new Label(0, 0, "URL");
    Label label1 = new Label(1, 0, "Text");
    Label label2 = new Label(0, 1, url);


    writableSheet.addCell(label);
    writableSheet.addCell(label1);
    writableSheet.addCell(label2);


    writableWorkbook.write();
    writableWorkbook.close();

    } catch (IOException e) {
    e.printStackTrace();
    } catch (RowsExceededException e) {
    e.printStackTrace();
    } catch (WriteException e) {
    e.printStackTrace();
    }
    }

    ReplyDelete
  12. hi, i have a written a code to retrieve data from excel file. in that while adding path..
    inputstream fis=new fileinputstream("file path");
    here im getting an exception like filenotfoundexception. after i thorow that one again while writing the code to retrieve data from excel file...
    workbook wb=WorkbookFactory.create(fis);
    here im getting an exception like IOexception and Invalidformatexception. if i throw these they are replacing the filenotfoundexception and while running the program im getting an error like...
    Exception in thread "main" java.io.FileNotFoundException: D:\testing\webdriver\testing (The system cannot find the file specified)

    please suggest me how to solve this problem.

    Thank you

    ReplyDelete
  13. Hi Ankit,

    Please forgive me for the late reply.
    First ur code, String tt=wDriver.findElement(By.xpath("//*[@id='videogallery']/a[position() = " + i +"]")).getText();
    writeurl(tt);

    Instead of text, if u pass tt, it will work i think. Please check your scripts

    Thanks,
    Arun

    ReplyDelete
  14. Hi padma,

    Do you given your path like this c:\\Test\\path? I mean with \\ format?

    Are you getting error in compile time or run time?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hi Arun,

      yes, i have given the path like this "D:\\testing\\toolking\\testdata.xls"
      and checked. but still it's not working. im getting the same error filenotfoundexception at run time.

      Thanks,
      padma

      Delete
    3. Can you share your code here? Have you imported JXL jar file?

      Delete
    4. This comment has been removed by the author.

      Delete
  15. Writing data to excel code is working proper.
    Thank you.

    ReplyDelete
  16. Hi,
    I am unable to read the information from excel file aswell as create an excel file in the required location.
    When trying to read the data from an excel file it is throwing "FileNotFound" exception.

    InputStream fis = new FileInputStream("Path of the file");
    Workbook wb=WorkbookFactory.create(fis);

    I am using excel 2003 version.Can any one help me correct syntax.

    Whether to import ss, hssf. But,either of them are working.

    ReplyDelete
    Replies
    1. I am srry....i meant to say, either of them are not working...

      Delete
  17. I really need help on this:
    my code is below:
    in my excel log, i want to get 3 types of getText items. But somehow its priting only one becuase my 2nd method getText () passing only one parameter which is (String hasan)where i want to see 3 out put which is description, orderNo and amount. since my getText () passing only one paramenter so i am only one output which print 3 times in my excel log. but i am looking 3 differrent output in my log. as you can see i pass 3 diffrent types of parameter in my outExcel ().


    public void outExcel (String locator, String locator2, String locator3) throws Exception {


    String description = driver.findElement(By.xpath (locator)).getText();
    getText (description);
    String orderNo = driver.findElement(By.xpath (locator2)).getText();
    getText(orderNo);
    String amount = driver.findElement(By.xpath (locator3)).getText();
    getText(amount);
    }
    public void getText(String hasan)
    {
    try
    {
    FileOutputStream f = new FileOutputStream("C:\\Users\\hassan.abul\\Desktop\\orderNo.xls",true);
    WritableWorkbook book = Workbook.createWorkbook(f);
    WritableSheet sheet = book.createSheet("output", 0);

    Label description = new Label(0, 1, hasan);
    sheet.addCell(description);

    Label orderNo = new Label(1, 1, hasan);
    sheet.addCell(orderNo);

    Label amount = new Label(2, 1, hasan);
    sheet.addCell(amount);

    book.write();
    book.close();
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    }

    ReplyDelete
  18. Hi all... i am very new to Selenium, indeed, i learned selenium on my own.
    I have a requirement:

    1. Use login credentials from excel sheet and get logged-in
    2. if test is passed, write "Passed" to excel,
    else, write it as "Failed"

    Actually, point-1 is working fine for me.. can any one help me with point-2

    (Note: I am using Selenium 2.0/TestNG/JXL)

    ReplyDelete
    Replies
    1. Sorry for adding a new point here,

      This results should be added to existing excel, but not a new excel every time.

      Delete
  19. Hi,
    I'm facing some problem while "creating new workbook & new work sheet & writing values in it" please help me.The following is my code.
    package project1;

    import java.awt.Label;

    import jxl.Workbook;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    import jxl.write.biff.File;

    public class excel_write_operations {

    public static void main(String[] args) {
    WritableWorkbook wwb=Workbook.createWorkbook(new File("G:\\wroptions.xls"));
    WritableSheet ws=wwb.createSheet("one",0);
    for(int i=0; i<10; i++)
    {
    jxl.write.Label la=new jxl.write.Label(0,i,"options");
    ws.addCell(la);
    }
    }

    }

    ReplyDelete
  20. the above code was not working can you please help me how to write the result in excel sheet

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete
  23. Label l = new Label(0, 0, text);
    sheet.addCell(l);
    its showing error

    ReplyDelete
  24. for(int i=1; i<totalrow; i+=5)
    {
    Row row = sheet.getRow(i);//get row
    if (download.isDisplayed())
    {
    FileOutputStream fos = new FileOutputStream(excelpath);
    String value = "PASS";
    Cell cellresult;
    cellresult = row.createCell(14);
    cellresult = row.getCell(14);
    cellresult.setCellValue(value);
    workbook.write(fos);
    fos.flush();
    fos.close();
    log.info("Result save into sheet\n");
    Thread.sleep(wait/2);
    workbook.close();
    }

    getting error for workbook.write(fos); line



    ReplyDelete
  25. Good one and you can try this too buddy.
    This code will work for reading data from excel sheet :

    import java.io.IOException;
    import org.testng.annotations.Test;
    import jxl.Sheet;
    import jxl.Workbook;
    import jxl.read.biff.BiffException;
    @Test
    public class Xlsheet {
    public void asd() throws IOException, BiffException, Throwable{
    Workbook workbook = Workbook.getWorkbook(new File ("FilePath"));
    System.out.println(workbook);
    Sheet sheet = workbook.getSheet("Sheet1");
    System.out.println(sheet.getRows());

    String s = sheet.getCell(1,1).getContents();
    System.out.println(s);
    }
    }
    This code will work for Writing data into excel sheet :

    package sample;
    import java.io.FileOutputStream;
    import org.testng.annotations.Test;
    import jxl.Workbook;
    import jxl.write.WritableWorkbook;
    import jxl.write.WritableSheet;
    import jxl.write.Label;
    @Test
    public class ExcelWrite {
    public void aa() throws Throwable{

    //Creating an excel and naming it.

    FileOutputStream exlFileName= new FileOutputStream("Filepath");

    //Creating an instance for the above excel.

    WritableWorkbook exlWorkBook = Workbook.createWorkbook(exlFileName);

    //Creating Writable work sheets for the above excel.

    WritableSheet exlWorkSheet1 = exlWorkBook.createSheet("Shivaprsad",0);
    WritableSheet exlWorkSheet2 = exlWorkBook.createSheet("Suresh",1);

    //Creating data(cell values) into above excel workbook

    Label Sheet1cellContent = new Label(0,0,"Test sheet1");
    Label Sheet2cellContent = new Label(0,0,"Test sheet2");

    //Adding cell value to its respective sheet.

    exlWorkSheet1.addCell(Sheet1cellContent);
    exlWorkSheet2.addCell(Sheet2cellContent);

    //Writing the values into excel.

    exlWorkBook.write();

    //Close the workbook

    exlWorkBook.close();
    }
    }
    If your audience is also interested in Selenium Testing, they can take a look here:
    Selenium Training

    ReplyDelete
  26. can you please share the code in selenium c#.

    Thanks
    pradeep

    ReplyDelete
  27. hai.... i want to transfer only certain rows and columns from webtable to excel sheet... can u please help me with this..

    ReplyDelete
  28. Awesome post. Really you are shared very informative concept... Thank you for sharing. Keep on
    updating...

    datesheet-nic
    Education

    ReplyDelete
  29. Hello, I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
    Android Training in Chennai | Best Android Training in Chennai
    Matlab Training in Chennai | Best Matlab Training in Chennai
    Best AWS Training in Chennai | AWS Training in Chennai
    Selenium Training in Chennai | Best Selenium Training in chennai
    Devops Course Training in Chennai | Best Devops Training in Chennai

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. I can’t imagine that’s a great post. Thanks for sharing.

    Softgen Infotech is the best SAP Training in Bangalore , providing SAP Courses with 100% placement support. Our Centre has Certified Trainers who are working Professionals with more than 10 Years of real time experience on SAP Projects.

    ReplyDelete