Monday 17 February 2014

Reading and writing data from Excel using Selenium Web driver

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();
}
}