i want my program to read a single line (which will contain a URL) from excel file. Go to that URL and read next line -->go to the URL untill entire file is read.
import java.io.*;
import java.util.concurrent.TimeUnit;
import org.apache.poi.hssf.usermodel.*;
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.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class readDataFromExcelFile{
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
WebElement searchbox = driver.findElement(By.name("q"));
try {
FileInputStream file = new FileInputStream(new File("E://TestData.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i=1; i <= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchbox.sendKeys(keyword);
searchbox.submit();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
}
file.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
But the above program will get all the /urls at a single time. Can you please tell me what should i modify in the code.
Clear the field before typing more text into it.
sendKeys() does just what it says: It sends a series of "user pressed key X" to the browser. So if the field already contains content, then the new keys are appended.
See: Clear text from textarea with selenium
Related
I am trying to do data driven testing and I am not able to figure it out why I am getting data mismatch. I am trying to automate just usernames and that is in form of string. Can you please review my code and tell me what I am doing wrong?
Below are two files. one is my main method file and one is my excel config file. I have also attached screenshot of my error. Any help would be appreciated. Thank you.
File1:
`
package loginAdmin;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class PersonateUser {
#Test(dataProvider="testdata")
public void login(String username) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver",
C:\\Users\\abc\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(200, TimeUnit.SECONDS);
driver.get("www.abc.com/AdminHome.aspx");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtLoginName")).
sendKeys("admin");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtPassword")).
sendKeys("Password");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_cmdContinue")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_lblUserName")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_txtUserName")).
sendKeys(username);
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_btnSearch")).click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_resultsGrid_ctl02_LogInAsUser")).
click();
System.out.println("User is able to login successfully");
driver.findElement(By.xpath("/html/body/form/div[3]/div[3]/div[1]/div[1]/div/div[5]/ul/li[6]/a")).
click();
#DataProvider(name="testdata")
public Object[][] TestDataFeed()
{
ReadExcelFile config = new
ReadExcelFile("C:\\Users\\abc\\eclipseworkspace\\Login\\testdata\\testdata.xlsx");
int rows = config.getRowCount(0);
Object[][] credentials = new Object[rows][2];
for(int i = 0; i < rows; i++)
{
credentials[i][0] = config.getData(0, i, 0);
}
return credentials;
}
}
`
File 2:
` package loginAdmin;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile
{
XSSFWorkbook wb;
XSSFSheet sheet;
public ReadExcelFile(String excelPath)
{
try
{
File src = new File(excelPath);
FileInputStream fis = new FileInputStream(src);
wb =new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
sheet= wb.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex)
{
int row = wb.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}
}
`
Error Screenshot:
Excel File:
You are declaring Object[][] credentials = new Object[rows][2]; but you fill only one column keeping other column empty (null). Hence the dimension of your array does not match the number of arguments your method accepts.
Fix it with changing that line to:
Object[][] credentials = new Object[rows][1];
Using windows-7 and keep getting errors to write code to ready excel
Trying to read excel data file in java maven Keep getting error on
line#49 sheet= book.getSheet(sheetname); I have added all dependencies and imported but still can not clear this error.
package com.newTour.qa.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hslf.model.Sheet;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.newTour.qa.Base.TestBase;
public class TestUtil extends TestBase {
public static String TESTDATA_SHEET_PATH = "C:\\Users\\shahgee\\newtour.qu\\src\\main\\java\\"
+ "com\\qa\\newtour\\testdata\\MercutyTourTestData.xlsx" ;
static Workbook book;
static Sheet sheet;
public static Object[][]getTestData(String sheetname){
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book= WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetname);
Object[][]data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for (int i =0; i <sheet.getLastRowNum();i++){
for (int k =0;k <sheet.getRow(0).getLastCellNum(); k++){
data[i][k]= sheet.getRow(i+1).getCell(k).toString();
}
}
return data;
}
}
try to change the import of Sheet class with
org.apache.poi.ss.usermodel.Sheet
what you use right now is Sheet for Powerpoint Document.
here the reference of the library you use right now:
https://www.oschina.net/uploads/doc/poi-3.1-FINAL/org/apache/poi/hslf/model/Sheet.html
I Was Executing Test Scripts Though Excel Sheet Using Keyword Driven Data Framework.
While Executing Am Geting Error as :
java.lang.RuntimeException: java.lang.IllegalStateException: Cannot
get a STRING value from a NUMERIC cell
My Selenium Code is
package DemoData;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import DataConfig.ExcelDataConfig;
public class ReadArrayData
{
WebDriver driver;
#Test(dataProvider="Tipreports")
public void Dataprovider(String username, String password) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://xxxxxxxxxxxxxxxx/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.id("txt_username")).sendKeys(username);
driver.findElement(By.id("txt_pin")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='btn_click']")).click();
Thread.sleep(5000);
//driver.getCurrentUrl();
Assert.assertTrue(driver.getCurrentUrl().contains("http://xxxxxxxxxxxxx/Algorithm_Run.aspx"),"User Not able to Login - Invalid Credentials");
}
#AfterMethod
public void Close()
{
driver.quit();
}
#DataProvider(name="Tipreports")
public Object[][] passdata()
{
ExcelDataConfig config = new ExcelDataConfig("E:\\Workspace\\KeywordFramework\\TestData\\Dataprovider.xlsx");
int rows = config.getRowCount(0);
Object[][] data = new Object[rows][2];
for(int i=0;i<rows;i++)
{
data[i][0]=config.getData(0, i, 0);
data[i][1]=config.getData(0, i, 1);
}
return data;
}
}
Here is My Excel Data Config Code :
package DataConfig;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDataConfig
{
XSSFWorkbook wb;
XSSFSheet Sheet1;
public ExcelDataConfig(String excelpath)
{
try
{
File src = new File(excelpath);
FileInputStream fis = new FileInputStream(src);
wb= new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
Sheet1 = wb.getSheetAt(sheetnumber);
String data =Sheet1.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetindex)
{
int row = wb.getSheetAt(sheetindex).getLastRowNum();
row = row+1;
return row;
}
}
Can you please help me to sort out this, Why am getting this error? I have declared 2 Columns and 4 Rows using for loop. But am getting cannot Get The error as cannot get the string value from Numeic Cell.
Try this:
String data;
if(cell.getCellType()==CellType.STRING)
data = cell.getStringCellValue();
else if(cell.getCellType()==CellType.NUMERIC)
data = String.valueOf(cell.getNumericCellValue());
else ...
It is a better way to retrieve the cell content as text.
Thanks to #AxelRichter, the manual show a more complete example to retrieve cell content: https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents
//try this:
DataFormatter objDefaultFormat = new DataFormatter();
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
String cellValueStr = objDefaultFormat.formatCellValue( cell , formulaEvaluator );
DataFormatter contains methods for formatting the value stored in an Cell. This can be useful when you need to get data exactly as it appears in Excel.
Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.
Thanks to #AxelRichter:
DataFormatter formatter = new DataFormatter();
String text = formatter.formatCellValue(cell);
I am trying to write title and price into excel file. I am creating columns but java game me error 'NULL POINTER EXCEPTION' at line number 48, Please help me what is main reason.But if i write at line no 48 ,sheet1.getRow(0).createCell(0).getStringCellValue('Naqash');Then no Null pointer error is showing.
package codeclasses;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
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.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class ReadExcel {
List<WebElement> title, prices;
#Test
public void test() throws IOException {
System.setProperty("webdriver.chrome.driver", "h:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://themeforest.net/search/education?referrer=homepage&utf8=%E2%9C%93");
title = driver.findElements(By.xpath("//h3[#class = 'product-list__heading']/a"));
prices = driver.findElements(By.xpath("//p[#class='product-list__price-desktop']"));
File src = new File("./file/Book1.xlsx");
FileInputStream file = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet1 = wb.getSheetAt(0);
for (int i = 0; i < 30; i++) {
int j = 0;
if(sheet1.getRow(i+1)==null){
(48) sheet1.getRow(i+2).createCell(j).setCellValue("Naqash");
sheet1.getRow(i+2).createCell(j+1).setCellValue("Zafar");
}
else{
System.out.println("Cant find the scene");
}
FileOutputStream fileout = new FileOutputStream(src);
wb.write(fileout);
}
}
}
Try to create the row and cell before you insert data into it. For example:
int rowIndex = 0;
int columnIndex = 0;
Row row = sheet1.createRow(rowIndex);
Cell cell = row.createCell(columnIndex);
cell.setCellValue("Naqash");
You can get row by getRow(index) if you have already created it before
The issue is that you never test if the cell is null!
if (cell == null)
{
System.out.println("Cell is Empty in Column:" + cols);
}
else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
//code
}
As a general matter, you should be careful while handling Cell.getCellType() function, since an empty cell could be either null or be a CELL_TYPE_BLANK.
I hope it helped.
I have an excel sheet from where I am reading excel cel values and importing to DB
Using Apache POI :
if (row.getCell(8) != null) {
setActualDeparture(DateUtil.getJavaDate(row.getCell(8).getNumericCellValue()));
}
The excel sheet has null on Cell 8 , so it should not import anything . but it takes dates like 1899-12-31T00:00:00
What could be the issue ?
The Row.getCell(int cellnum) returns only NULL if there is nothing stored in the file for this cell. It returns the cell if there is something stored in the file for this cell. Even if this is only a NumberFormat for example or any other information for this cell.
But there is a second method Row.getCell(int cellnum, Row.MissingCellPolicy policy) http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell%28int,%20org.apache.poi.ss.usermodel.Row.MissingCellPolicy%29 which can be used in your case.
Example:
There is nothing in A1 but there is a special NumberFormat and not General applied.
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
class GetEmtyCellTest {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
System.out.println(row.getCell(0).getNumericCellValue()); //0.0
System.out.println(row.getCell(0, Row.RETURN_BLANK_AS_NULL)); //null
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}