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();
}
}
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();
}
}
while using this code showing error, for removing error which package I have have to import.
ReplyDeletePlease 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.............
Hi Rahul,
ReplyDeleteImport JXL jar file.... (Writable)
can you share the error message here?
there is an error in
ReplyDeleteLabel l = new .Label(0, 0, text);
it saying "Syntax error on token "new", invalid Expression".
thanks
Its working fine
ReplyDeleteimport jxl.write.Label and use Label l = new Label(0, 0, text);
Thanks
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
ReplyDeleteLabel l = new Label(0, 0, text);
sheet.addCell(l);
Its working. Use either
ReplyDelete1) import jxl.write.Label;
or
2) jxl.write.Label l = new Label(0, 0, text);
Thanks
I have used the same code to get Text of "Software testing" on wiki page
ReplyDeleteused 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"
Hi Ramesh,
ReplyDeleteUse Thread.sleep(in milliseconds); before writing the text
Thanks,
Arun
i used above code for write title in excel sheet..but there write junk data...how i solve this problem??
ReplyDeletedo i need to do entry as a column header in file before through selenium webdriver.
Hi Ankit,
ReplyDeleteNo need to put column header in file. For verifying, try to print the output in the application using System.out.println"(Title is "+s);
Hello ,
ReplyDeleteMy 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();
}
}
hi, i have a written a code to retrieve data from excel file. in that while adding path..
ReplyDeleteinputstream 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
Hi Ankit,
ReplyDeletePlease 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
Hi padma,
ReplyDeleteDo you given your path like this c:\\Test\\path? I mean with \\ format?
Are you getting error in compile time or run time?
This comment has been removed by the author.
DeleteHi Arun,
Deleteyes, 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
Can you share your code here? Have you imported JXL jar file?
DeleteThis comment has been removed by the author.
DeleteWriting data to excel code is working proper.
ReplyDeleteThank you.
Hi,
ReplyDeleteI 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.
I am srry....i meant to say, either of them are not working...
DeleteI really need help on this:
ReplyDeletemy 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();
}
}
Hi all... i am very new to Selenium, indeed, i learned selenium on my own.
ReplyDeleteI 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)
Sorry for adding a new point here,
DeleteThis results should be added to existing excel, but not a new excel every time.
Hi,
ReplyDeleteI'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);
}
}
}
the above code was not working can you please help me how to write the result in excel sheet
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteLabel l = new Label(0, 0, text);
ReplyDeletesheet.addCell(l);
its showing error
for(int i=1; i<totalrow; i+=5)
ReplyDelete{
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
Good one and you can try this too buddy.
ReplyDeleteThis 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
can you please share the code in selenium c#.
ReplyDeleteThanks
pradeep
hai.... i want to transfer only certain rows and columns from webtable to excel sheet... can u please help me with this..
ReplyDelete
ReplyDeleteGreat post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
automation anywhere training in chennai
automation anywhere training in bangalore
automation anywhere training in pune
automation anywhere online training
blueprism online training
rpa Training in sholinganallur
rpa Training in annanagar
iot-training-in-chennai
blueprism-training-in-pune
automation-anywhere-training-in-pune
Awesome post. Really you are shared very informative concept... Thank you for sharing. Keep on
ReplyDeleteupdating...
datesheet-nic
Education
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.
ReplyDeleteAndroid 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
This comment has been removed by the author.
ReplyDeletenice post...
ReplyDeleteAustralia hosting
Bermuda web hosting
Botswana hosting
mexico web hosting
moldova web hosting
albania web hosting
andorra hosting
armenia web hosting
australia web hosting
good post...
ReplyDeletedenmark web hosting
inplant training in chennai
I can’t imagine that’s a great post. Thanks for sharing.
ReplyDeleteSoftgen 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.
This is one of the best resources I have found in quite some time.
ReplyDeleteSalesforce Training | Online Course | Certification in chennai | Salesforce Training | Online Course | Certification in bangalore | Salesforce Training | Online Course | Certification in hyderabad | Salesforce Training | Online Course | Certification in pune
Thanks for sharing knowledge about selenium.Very much useful.
ReplyDeleteJava training in Chennai
Java training in Bangalore
Java training in Hyderabad
Java Training in Coimbatore
Java Online Training