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

5 comments:

  1. I am getting "Exception in thread "main" java.lang.NullPointerException".

    place of exlWorkSheet1.addCell(Sheet1cellContent);

    ReplyDelete
  2. Label Sheet2cellContent = new Label(0,1,"Test sheet2");

    ReplyDelete
  3. wow, happy to hear testing is you passion. For me too testing is my fashion. Good information you provided. So the same kind of way we have to use for all formats of file parsing? If your audience is also interested in Selenium Testing, they can take a look here:
    Selenium Training

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

    ReplyDelete
  5. how to write code for a sign up page and i need to enter details from excel

    ReplyDelete