Cannot get a STRING value from a NUMERIC cell? - java

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

Related

Tried to log in application with multiple users from the Excel sheet data provider. But No class found an error getting

The Selenium Webdriver, TestNG version & used libraries are given below.
Selenium version : selenium-server-standalone-3.41.59.jar
TestNG version : 7.4.0
Tried to login with Excel sheet data provider.But no class found error getting.
Added Apache POI excel related dependenices
Added Libraries(Please see the screenshot)
Here is my code.
The Selenium Webdriver, TestNG version & used libraries are given below.
Selenium version : selenium-server-standalone-3.41.59.jar TestNG version : 7.4.0
package ui;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class MultiUserLogin {
public static WebDriver driver;
public WebDriverWait wait;
String appURL1 = "https://www.google.com";
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.gecko.driver","E:/Geckdriver/geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider="LoginData")
public void VerifyValidLogin(String Username, String Password,String Company) {
driver.navigate().to(appURL1);
driver.findElement(By.id("userId")).sendKeys(Username);
driver.findElement(By.id("password")).sendKeys(Password);
driver.findElement(By.id("company")).sendKeys(Company);
driver.findElement(By.linkText("Login")).click();
}
#DataProvider(name="LoginData")
public Object[][] LoginData() throws Exception {
Object[][] testObjArray = ExcelUtils.getTableArray("E:\\TestNG\\TestData\\TestData.xlsx","Sheet1");
return (testObjArray);
}
}
package ui;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {
String[][] tabArray = null;
try {
FileInputStream ExcelFile = new FileInputStream(FilePath);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int startRow = 1;
int startCol = 1;
int ci,cj;
int totalRows = ExcelWSheet.getLastRowNum();
// function as well to get Column count
int totalCols = 2;
tabArray=new String[totalRows][totalCols];
ci=0;
for (int i=startRow;i<=totalRows;i++, ci++) {
cj=0;
for (int j=startCol;j<=totalCols;j++, cj++){
tabArray[ci][cj]=getCellData(i,j);
System.out.println(tabArray[ci][cj]);
}
}
}
catch (FileNotFoundException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
catch (IOException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
return(tabArray);
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
CellType dataType= Cell.getCellType();
if (dataType == CellType.STRING) {
return "";
}else{
String CellData = Cell.getStringCellValue();
return CellData;
}
}catch (Exception e){
System.out.println(e.getMessage());
throw (e);
}
}
}

Why I am getting Data Provider MisMatch error when I try to read from excel file?

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];

Null Pointer Exception if i try to create new Cell and write data into excel

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.

Code is not pasting the password value in the password field of the WebPage

The below code is fetching the emailId and password value from the source file and printing it on the console, but only pasting the emailId value in the web page, but not the password.
I am getting an error message as
FAILED: doLogin("gaurav_thantry#yahoo.com", "password1")
org.openqa.selenium.StaleElementReferenceException: stale element
reference: element is not attached to the page document
This is my code :
package excelSelenium;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
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.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class seleniumIntg {
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
XSSFRow row = null;
XSSFCell cell = null;
WebDriver driver = null;
#Test(dataProvider = "getData")
public void doLogin(String username, String password)
{
System.setProperty("webdriver.chrome.driver","C://testing/chromedriver_win32/chromedriver.exe" );
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/config/login?.src=fpctx&.intl=in&.lang=en-IN&.done=https://in.yahoo.com/%3fp=us");
driver.findElement(By.xpath("//input[#id='login-username']")).sendKeys(username);
driver.findElement(By.xpath("//*[#id='login-signin']")).click();
driver.findElement(By.xpath("//*[#id='login-passwd']")).sendKeys(password);
}
#DataProvider
public Object[][] getData() throws IOException
{
FileInputStream fis = new FileInputStream("C://Users/Gaurav/Documents/testid.xlsx");
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet("sheet1");
int rowCount = sheet.getFirstRowNum()+sheet.getLastRowNum()+1;
int colCount = sheet.getRow(0).getLastCellNum();
System.out.println("Row count is:" +rowCount+ "Col count is:" +colCount);
Object[][] data = new Object[rowCount-1][colCount];
for(int rNum = 2; rNum<=rowCount; rNum++)
for(int cNum = 0; cNum<colCount; cNum++)
{
System.out.println(getCellData("sheet1",cNum,rNum));
data[rNum-2][cNum]=getCellData("sheet1",cNum,rNum);
}
return data;
}
public String getCellData(String sheetName, int colNum, int rowNum)
{
try{
if(rowNum<=0)
return "";
int index = workbook.getSheetIndex(sheetName);
if(index == -1)
return "";
sheet =workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";
else if(cell.getCellTypeEnum()==CellType.STRING)
return cell.getStringCellValue();
else if(cell.getCellTypeEnum()==CellType.NUMERIC||cell.getCellTypeEnum()==CellType.FORMULA)
{String CellText = String.valueOf(cell.getNumericCellValue());
return CellText;}
else if(cell.getCellTypeEnum()==CellType.BLANK)
return "";
else return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e)
{
e.printStackTrace();
return "row"+rowNum+"col"+colNum+"Does not exist";
}
}
}
Add Explicit wait before entering password.
Try like below.
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/");
driver.findElement(By.xpath("//input[#id='login-username']")).sendKeys("Username");
driver.findElement(By.xpath("//*[#id='login-signin']")).click();
WebDriverWait wait = new WebDriverWait(driver,20);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id='login-passwd']")));
driver.findElement(By.xpath("//*[#id='login-passwd']")).sendKeys("Password");
It was working in my machine.Let me know if you have any queries

I am getting an error message saying that the static field "CELL_TYPE_***" should be accessed in a static way

I am getting an error message when I hover over the 'CELL_TYPE_****' methods in the method getCellData(), saying that 'the static field "CELL_TYPE_***" should be accessed in a static way' and a strike line over them.
package excelSelenium;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.xssf.usermodel.XSSFCell;
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.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class seleniumIntg {
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
XSSFRow Row = null;
XSSFCell Cell = null;
WebDriver driver = null;
#Test(dataProvider = "getData")
public void doLogin(String username, String password)
{
System.setProperty("webdriver.chrome.driver","C://testing/chromedriver_win32/chromedriver.exe" );
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://login.yahoo.com/config/login?.src=fpctx&.intl=in&.lang=en-IN&.done=https://in.yahoo.com/%3fp=us");
driver.findElement(By.xpath("//input[#id='login-username']")).sendKeys(username);
driver.findElement(By.xpath("//div[#class='mbr-login-submit']/button")).click();
driver.findElement(By.xpath("//input[#id='login-passwd']")).sendKeys(password);
}
#DataProvider
public Object[][] getData() throws IOException
{
FileInputStream fis = new FileInputStream("C://Users/Gaurav/Documents/testid.xlsx");
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet("sheet1");
int rowCount = sheet.getFirstRowNum()+sheet.getLastRowNum()+1;
int colCount = sheet.getRow(0).getLastCellNum();
System.out.println("Row count is:" +rowCount+ "Col count is:" +colCount);
Object[][] data = new Object[rowCount-1][colCount];
for(int rNum = 2; rNum<=rowCount; rNum++)
for(int cNum = 0; cNum<colCount; cNum++)
{
System.out.println(getCellData("sheet1",cNum,rNum));
data[rNum-2][cNum]=getCellData("sheet1",cNum,rNum);
}
return data;
}
public String getCellData(String sheetName, int colNum, int rowNum)
{
try{
if(rowNum<=0)
return "";
int index = workbook.getSheetIndex(sheetName);
if(index == -1)
return "";
sheet =workbook.getSheetAt(index);
Row = sheet.getRow(rowNum-1);
if(Row==null)
return "";
Cell = Row.getCell(colNum);
if(Cell==null)
return "";
else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
return Cell.getStringCellValue();
else if(Cell.getCellType()==Cell.CELL_TYPE_NUMERIC||Cell.getCellType()==Cell.CELL_TYPE_FORMULA)
{String CellText = String.valueOf(Cell.getNumericCellValue());
return CellText;}
else if(Cell.getCellType()==Cell.CELL_TYPE_BLANK)
return "";
else return String.valueOf(Cell.getBooleanCellValue());
}
catch(Exception e)
{
e.printStackTrace();
return "row"+rowNum+"col"+colNum+"Does not exist";
}
}
// TODO Auto-generated method stub
}
In instructions such as :
else if(Cell.getCellType()==Cell.CELL_TYPE_STRING)
despite appearances, Cell is an instance and not a class as you declare this field in your class:
XSSFCell Cell = null;
But static fields and methods have no need to be prefixed by an instance to call them but by the class.
So you should prefix the static fields you are referencing like that :
else if(Cell.getCellType()==XSSFCell.CELL_TYPE_STRING)
To avoid this kind of misleading code that gives the impression that you are using as prefix an instance while you are using actually a class, follow the Java code conventions that say among other things that variable names should start by a lowercase character.
This is better :
XSSFCell cell = null;
...
else if(cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
As a side note, the CELL_TYPE_STRING static field is deprecated since POI 3.15 beta 3.
You are advised to use the enum org.apache.poi.ss.usermodel.CellType.STRING instead of.
Well, first of all you should rename your variables, so that they start with lower-case letters (e.g. cell instead of Cell) to avoid confusion.
So cell is an instance of class XSSFCell which inherits from Cell.
The static fields e.g. CELL_TYPE_STRING are declared in the class Cell
: so you should use Cell.CELL_TYPE_STRING instead of cell.CELL_TYPE_STRING

Categories