Tuesday, 9 September 2014

Reading and writing data from Excel using Selenium Web driver

This code will work for reading data from excel sheet :
 package TestNg;
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{

//To name the path of file it is stored

  Workbook workbook = Workbook.getWorkbook(new File ("D:\\seleniumworkspace\\SeleniumWebapplications\\src\\TestNG\\excel.xls"));
  System.out.println(workbook);

///To get the sheet name
  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 TestNG;
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 the path of excel where it is located

FileOutputStream exlFileName= new FileOutputStream("D:\\seleniumworkspace\\SeleniumWebapplications\\src\\TestNG\\excel.xls");

//Creating an instance for the above excel.

WritableWorkbook exlWorkBook = Workbook.createWorkbook(exlFileName);

//Creating Writable work sheets for the above excel.

WritableSheet exlWorkSheet1 = exlWorkBook.createSheet("abhishek",0);
WritableSheet exlWorkSheet2 = exlWorkBook.createSheet("Pruthvi",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();
}

}



To know FAQ's in Interviews on Selenium Please ClickHere
To know more on SQL Queries Required For Testers Please  ClickHere

No comments:

Post a Comment