Please help!. Am newbie with Selenium frameworks, I have a method that accepts 5 parameters for booking a party. It uses TestNG DataProvider to read from excel file. The problem is(as shown below) It uses JXL imports which only supports XLS files (excel 2003 or older). I need help with a similar code that uses Apache POI instead so that it will support XLSX and new versions of excel (2007+). Can someone help me please?
package com.suite1;
import util.TestUtil;
import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class CreatePartyTest extends TestBase1 {
Workbook wb;
Sheet sh1;
int numrow;
#BeforeTest
public void beforeTest() throws IOException
{
initialize();
if (TestUtil.isSkip("CreatePartyTest"))
{
throw new SkipException("Skipping test, check run mode");
}
dr.get(CONFIG.getProperty("testSiteName"));
getobject("signin_link").click();
getobject("username_Signin_input").sendKeys("alexy.dsouza");
getobject("password_input").sendKeys("testing123");
getobject("submit_button").click();
}
#Test(dataProvider="Partydata")
public void createParty (String Partyname, String Date, String Firstname, String Lastname, String email, String mobile) throws InterruptedException
{
getobject("party_link").click();
getobject("start_party_link").click();
getobject("partyname_input").sendKeys(Partyname);
getobject("partydate_input").sendKeys(Date);
getobject("hostfirstname_input").sendKeys(Firstname);
getobject("hostlastname_input").sendKeys(Lastname);
getobject("hostemail_input").sendKeys(email);
getobject("hostmobile_input").sendKeys(mobile);
getobject("make_reservation").click();
}
//source
#DataProvider(name="Partydata")
public Object[][] TestDataFeed(){
try {
// load workbook: this is where i store my excel
wb=Workbook.getWorkbook(new File("C://Workspace//Max//excelfiles//Partydata.xls"));
// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);
// get number of rows so that we can run loop based on this
numrow= sh1.getRows();
}
catch (Exception e)
{
e.printStackTrace();
}
// Create 2 D array and pass row and columns
Object [][] Accountdata=new Object[numrow-1][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0,j=1;i<numrow-1;i++){
// Fetch first row Accountname
Accountdata[i][0]=sh1.getCell(0,j).getContents();
// Fetch first row BankName
Accountdata[i][1]=sh1.getCell(1,j).getContents();
// Fetch everything else before an empty column
Accountdata[i][2]=sh1.getCell(2,j).getContents();
Accountdata[i][3]=sh1.getCell(3,j).getContents();
Accountdata[i][4]=sh1.getCell(4,j++).getContents();
}// Return 2d array object so that test script can use the same
return Accountdata;
}
}
I cannot solve your exact query , but you can take reference from my code in which i have used .xlsx workbook only and it is working fine for me.
I am able to read data from excel sheet(.xlsx) .
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProvidersConcept {
#DataProvider(name="Excelsheet")
public Object[][] readData() throws Exception
{
File f = new File("C:/Users/Vikrant/Documents/MavenTesting.xlsx");
FileInputStream fis = new FileInputStream(f);
XSSFWorkbook workBook = (XSSFWorkbook) WorkbookFactory.create(fis);
XSSFSheet sheet=workBook.getSheet("Sheet1");
Object array[][]=new Object[2][2];
for(int i =0;i<2;i++)
{
for( int j=0;j<2;j++)
{
array[i][j]=sheet.getRow(i).getCell(j).toString();
}
}
return array;
}
#Test(dataProvider="Excelsheet")
public void testData(String Username , String password)
{
System.out.println(Username);
System.out.println("Username tested successfully");
System.out.println(password);
System.out.println("password tested successfully");
}
}
enter code here
Related
I am trying to download a file using java selenium. The download button is clicked and it takes time to initiate and complete the download from the website (time of download depends on size of file and speed of net).
However, the next code is executed immediately after the code driver.findElement(By.xpath("//*[#id='downloadReport']/div")).click(); without waiting for download to complete.
The file name is dynamic (different file name based on search data extracted from excel sheet SearchData.xls
Any help is highly appreciated.
The code is as under:-
package Basic;
import java.awt.AWTException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Calendar;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class sftest2 {
public static void main(String[] args) throws IOException, InterruptedException, AWTException {
System.setProperty("webdriver.edge.driver", "D:\\Installer\\msedgedriver.exe");
File file = new File("D:\\SearchData\\SearchData.xls");
FileInputStream inputStream = new FileInputStream(file);
HSSFWorkbook wb=new HSSFWorkbook(inputStream);
HSSFSheet sheet=wb.getSheet("SF_NSF");
int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();
WebDriver driver = new EdgeDriver();
driver.manage().window().maximize();
driver.get("https://******************");
driver.navigate().to("https://******************************");
for(int i=1;i<=rowCount;i++) {
driver.findElement(By.name("cAccount")).sendKeys("Search");
driver.findElement(By.xpath("//*[#id='abcSearchAction']/div[1]/div[3]/div[4]/img")).click();
WebElement bName=driver.findElement(By.id("bName"));
borrowerName.sendKeys(sheet.getRow(i).getCell(0).getStringCellValue());
driver.findElement(By.xpath("//*[#id='search-button']/ul/li[1]/div/input")).click();
Thread.sleep(2000);
driver.navigate().refresh();
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(20));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[#id=\'load_projectTable\']")));
if(driver.getPageSource().contains("View 1 -"))
{
driver.findElement(By.xpath("//*[#id='downloadReport']/div")).click();
Thread.sleep(50000); // Doesnot want to wait for specified time, the next code should execute immediately after complete download of file called through above code
driver.findElement(By.xpath("//*[#id='footer-container']/div[3]/a")).click();
}
else
{
//driver.findElement(By.xpath("//*[#id='three-icons']/ul/li[3]/a/div")).click();
Calendar cal = Calendar.getInstance();
java.util.Date time = cal.getTime();
String timestamp = time.toString().replace(":", "").replace(" ", "");
System.out.println(time);
System.out.println(timestamp);
TakesScreenshot ts = (TakesScreenshot)driver;
File src=ts.getScreenshotAs(OutputType.FILE);
File trg=new File(".\\screenshots\\SF_1Cr_B_Search_"+timestamp+".png");
FileUtils.copyFile(src,trg);
//Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='footer-container']/div[3]/a")).click();
}
}
//Close the workbook
wb.close();
//Quit the driver
driver.quit();
}
}
import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.write.*;
import jxl.write.Number.*;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class reader {
public static void main(String args[]) throws IOException, WriteException, BiffException {
String inputFile = "C:\\Users\\Chemeris\\Documents\\Book1.xls";
File inputWorkbook = new File(inputFile);
Workbook w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
//Ading a label
Label label = new Label(2,2, "Hello");
sheet.addCell(label);
w.write();
w.close();
}
}
I get a cannot find symbol error on ".addCell" and on ".write".
If you can help me solve this problem or offer another solution to wrting to an existing excel file I would be most thankfull
You may try to use ApachePOI to get the same result. There are bunch of documents https://www.tutorialspoint.com/apache_poi/)
I am trying to Pull date format MM/DD/YYYY from Microsoft Excel 97-2003 Worksheet and populate in the web field cause switch month and day to each other place and that cause script failure.
I want to populate date in the MM/DD/YYYY format(American Format) in the web field. However, in the web field date populate as DD/MM/YYYY.
Following date format I have in my excel sheet:
10/18/1976
When date populate in the web field then it populate as below:
18/10/1976
Following are my code:
package com.Test
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TC20042 extends BaseClass{
#Test
public void registration() throws Exception, InterruptedException {
FileInputStream fi=new FileInputStream("C:\\File\\Book2.xls");
Workbook w=Workbook.getWorkbook(fi);
Sheet s=w.getSheet(2);
try
{
for (int i = 0; i < s.getRows(); i++)
{
//Read data from excel sheet
String s7 = s.getCell(6,i).getContents();
driver.findElement(By.xpath("//*[#id='__o3id9']")).sendKeys(s7);
Thread.sleep(500);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
I just noticed that I was using Default date format in the excel sheet when I entered test data in the excel sheet as below:
But then I realized that may be there is another customize date format in the cell format option which I updated as below and it worked for me now:
I'm fairly new to Selenium webdriver and Java, previously I used Selenium IDE. I'm trying to read testdata from an Excel sheet. Which is then written to Eclipse console, which works, and should be used to execute the actual test, which doesn't work. The actual test is not executed because I get an error argument type mismatch. The code looks like this:
package Test_Excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
#RunWith(Parameterized.class)
public class TestWithExcelData {
// Our two parameters
private final int input;
private final int resultExpected;
// Constructor
public TestWithExcelData(int input, int result) {
this.input = input;
this.resultExpected = result;
}
#Parameters
public static Iterable<Object []> data() throws BiffException, IOException
{
String FilePath = "C://Selenium//workspace//testproject//src//testdata//TestData.xls";
FileInputStream fs = new FileInputStream(FilePath);
Object[][] object = new Object[6][2];
Workbook wb = Workbook.getWorkbook(fs);
//locate the excel file in the local machine
Sheet sheet = wb.getSheet("IOResult");
int i=1; //avoid header row
while(!(sheet.getCell(0, i).getContents().equals("end"))) //read data till it reaches the cell whose text is ‘end’
{
object[i-1][0]=sheet.getCell(0, i).getContents();
object[i-1][1]=sheet.getCell(1, i).getContents();
System.out.print(sheet.getCell(0, i).getContents() + "\t");
System.out.print(sheet.getCell(1, i).getContents() + "\t");
System.out.println();
i++;
}
return Arrays.asList(object);
}
#Test
public void testSquareOff(){
Assert.assertEquals(resultExpected, MathUtils.square(input));
}
}
Is there somebody who can point me in the right direction?
Thanks in advance
The method sheet.getCell(column, row).getContents() is returning a String, but your constructor expects int.
You may modify the two lines in the data() method:
object[i-1][0] = Integer.valueOf(sheet.getCell(0, i).getContents());
object[i-1][1] = Integer.valueOf(sheet.getCell(1, i).getContents());
Using Selenium, I have written the below code to read data from an Excel sheet and key in an email and password into Facebook's login page. Error is Unhandled expression to use try/catch. How can I resolve this?
package Excelpack;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ClassTwo {
WebDriver driver;
String username;
String password;
#Test(dataProvider="testdata")
public void testFireFox(String uname, String password1){
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(uname);
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(password1);
}
#DataProvider(name="testdata")
public Object[][] TestDataFeed1()
{
FileInputStream fis=new FileInputStream("D:\\book3.xlsx");
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh1= wb.getSheetAt(0);
int numrow = sh1.getLastRowNum()-sh1.getFirstRowNum();
int colnum =sh1.getRow(1).getLastCellNum()+1;
Object [][] facebookdata=new Object[numrow][colnum];
for(int i=0;i<numrow;i++)
{
facebookdata[i][0]=sh1.getRow(0).getCell(i).getStringCellValue();
facebookdata[i][1]=sh1.getRow(1).getCell(i).getStringCellValue();
}
return facebookdata;
}
#BeforeTest
public void Setup(){
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com/");
}
}
If you are using any IDE like eclipse or intellijI then IDE would prompt you with the solution as to add "throws necessary exception" or write the block of code in try/catch. from the looks of the code it seems you would need to declare throws exception on your dataprovider TestDataFeed1.