How to read an Excel file in java with DataProvider - java

I have trouble reading the information in an Excel file to introduce and test with selenium. But the result always NullPoInterException. I tried to change the link in the Excel file. Here’s the 2-part code.
public class TestProviderII {
public static void main(String[] args) {
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
testData(url, "SheetOne");
}
public static void testData(String url, String sheet) {
ExcelUtils excelUtils = new ExcelUtils(url, sheet);
int rowCount = excelUtils.getRowCount();
int colCount = excelUtils.getColCount();
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
String cellData = excelUtils.getCellDataString(i, j);
System.out.println("Data : " + cellData);
}
}
}
}
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
static XSSFWorkbook workbook;
static XSSFSheet sheet;
public ExcelUtils(String workBook, String sheetName) {
try {
workbook = new XSSFWorkbook(workBook);
sheet = workbook.getSheet(sheetName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getRowCount() {
int rowCount = 0;
try {
rowCount = sheet.getPhysicalNumberOfRows();
System.out.println("No of Row : " + rowCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return rowCount;
}
public static int getColCount() {
int colCount = 0;
try {
colCount = sheet.getRow(0).getPhysicalNumberOfCells();
System.out.println("No of Column" + colCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return colCount;
}
public static String getCellDataString(int rowNum, int colNum) {
String cellData = "";
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getStringCellValue();
System.out.println("Data Cell : " + cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
public static Double getCellDataNumber(int rowNum, int colNum) {
double cellData = 0;
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getNumericCellValue();
System.out.println(cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
}
And the result is NullPointerException
null
null
null
null
java.lang.NullPointerException
at test.ExcelUtils.getRowCount(ExcelUtils.java:23)
at test.TestProviderII.testData(TestProviderII.java:12)
at test.TestProviderII.main(TestProviderII.java:7)
java.lang.NullPointerException
at test.ExcelUtils.getColCount(ExcelUtils.java:36)
at test.TestProviderII.testData(TestProviderII.java:13)
at test.TestProviderII.main(TestProviderII.java:7)
Process finished with exit code 0
Why the result nullPointerException despite I did exactly what said?
And I changed the Excel file link and the result is the same.
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
String url = "src\\test\\resources\\dataProvider.xlsx";
String url = "C:\\Selenuim\\demoApplication\\src\\test\\resources\\dataProvider.xlsx

Change below line:
testData(url, "SheetOne");
to:
testData(url, "Sheet1");
Assuming the sheet looks like below in your excel file:
Also ensure, there is some data in your excel sheet. I ran your code by just changing to Sheet1. And it worked see below:
Excel sheet:
Console Output:
No of Column3
Data Cell : d
Data : d
Data Cell : e
Data : e
Data Cell : f
Data : f

Related

Read three column and write two column in excel using selenium java

I need to read three columns as Name, Empid and empcode from excel, insert into textbox and save the record then setid & reqid fields are generated. Now save the setid and reqid after the Name,Empid and empcode in the same excel. I have tried any code from the internet but not much is working.
Below code for writing in excel
public static XSSFWorkbook wb;
public static XSSFSheet sheet;
public static FileInputStream fs;
public static FileOutputStream out;
public void WriteExcelFile()
{
String str1 = ackgreqid1.getText();
File file = new File(System.getProperty("user.dir") + "/src/main/java/com/testdata/FreeTestData.xlsx");
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
wb = new XSSFWorkbook(fs);
sheet = wb.getSheet("TestData");
} catch (IOException e) {
System.out.println("unable to find workbook or worksheet");
e.printStackTrace();
}
Iterator<Row> sheetrow = sheet.rowIterator();
// Row firstRow = sheetrow.next();
// int rowCount = sheet.getLastRowNum();
// = firstRow.cellIterator();
// Iterator<Cell> cell = firstRow.cellIterator();
while (sheetrow.hasNext()) {
Row value = sheetrow.next();
// System.out.println(value);
Iterator<Cell> cell = value.cellIterator();
Cell cellValue = cell.next();
String cellData = cellValue.getStringCellValue();
while (cell.hasNext()) {
if (cellData.equalsIgnoreCase("Step-Up")) {
int lastCellNum = value.getLastCellNum();
// System.out.println(lastCellNum);
Cell createCell = value.createCell(lastCellNum);
createCell.setCellValue(str1);
try {
out = new FileOutputStream(file);
wb.write(out);
// cell.next();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
break;
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
break;
}
}

How to set the excel file's visibility to true

I am creating a new excel file using Apache POI and I would like to set the file's visibility to true. What function or code do I use to show the file after I create it using Apache POI rather than just saving it in a directory?
I have tried the following line of code which is similar to what we use in LotusScript but I got a "Instance member VISIBLE does not exist" error on that line.
ExcelApplication.Visible = True
Below is the code I'm using to write the excel file, which does work correctly as it saves the file in the directory I specified in the 'fileName'.
public boolean writeExcelFile(String fileName) {
try {
//Auto fit content
for(int i = 0; i < 20; i++) {
this.wbSheet.autoSizeColumn((short)i);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(fileName);
this.wb.write(fileOut);
fileOut.close();
} catch(Exception ex) {
ex.printStackTrace();
return(false);
}
return(true);
}
I expect the excel file to be created and opened rather than saved on the computer.
The VBA code line ExcelApplication.Visible = True, where ExcelApplication would must be an Application object, can only work because VBA works directly together with the Microsoft Office applications. This is not what apache poi is doing. Apache poi's goal is creating files in the Microsoft Office file formats. Neither it needs any installed Microsoft Office application nor it tries to interact with those applications.
So after apache poi is ready with it's work, then you always will get a file in the appropriate Microsoft Office file format. The only thng you could do then is opening that file using java.awt.Desktop. For example:
public boolean openExcelFile(String fileName) {
try {
File file = new File(fileName);
Desktop.getDesktop().open(file);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
Complete Example:
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.GregorianCalendar;
import java.awt.Desktop;
class CreateExcelAndOpenFile {
private Workbook workbook;
private Sheet sheet;
public CreateExcelAndOpenFile() {
this.workbook = new XSSFWorkbook();
this.sheet = this.workbook.createSheet();
}
public Workbook getWorkbook() {
return this.workbook;
}
public boolean writeDataInSheet(Object[][] data, String[] columnCellTypes, CellStyle[] columnCellStyles) {
try {
FormulaEvaluator formulaEvaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
for (int r = 0; r < data.length; r++) {
Row row = this.sheet.createRow(r);
for (int c = 0; c < data[0].length; c++) {
Cell cell = row.createCell(c);
if (r == 0) {
cell.setCellValue((String)data[r][c]); // header row, all String
cell.setCellStyle(columnCellStyles[c]);
} else if ("number".equals(columnCellTypes[c]) && data[r][c] instanceof Double) {
cell.setCellValue((Double)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("date".equals(columnCellTypes[c]) && data[r][c] instanceof GregorianCalendar) {
cell.setCellValue((GregorianCalendar)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("text".equals(columnCellTypes[c]) && data[r][c] instanceof String) {
cell.setCellValue((String)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("formula".equals(columnCellTypes[c]) && data[r][c] instanceof String) {
cell.setCellFormula((String)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
formulaEvaluator.evaluateFormulaCell(cell);
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean writeExcelFile(String fileName) {
try (FileOutputStream fileOut = new FileOutputStream(fileName) ) {
// auto fit content
int columnsCountInHeaderRow = this.sheet.getRow(0).getLastCellNum();
for(int i = 0; i < columnsCountInHeaderRow; i++) {
this.sheet.autoSizeColumn((short)i);
}
// write the output to a file
this.workbook.write(fileOut);
this.workbook.close();
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean openExcelFile(String fileName) {
try {
File file = new File(fileName);
Desktop.getDesktop().open(file);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
String fileName = "./Excel.xlsx";
CreateExcelAndOpenFile application = new CreateExcelAndOpenFile();
Object[][] data = new Object[][] {
new Object[] {"Name", "Value", "Date", "Formatted value", "Formula"},
new Object[] {"Lorem", 123.456789, new GregorianCalendar(2019, 0, 15), 123.456789, "ROUND(B2,2)"},
new Object[] {"Ipsum", 1234.56789, new GregorianCalendar(2019, 5, 15), 1234.56789, "ROUND(B3,2)"}
};
String[] columnCellTypes = new String[]{"text", "number", "date", "number", "formula"};
DataFormat dataFormat = application.getWorkbook().createDataFormat();
CellStyle dateStyle = application.getWorkbook().createCellStyle();
dateStyle.setDataFormat(dataFormat.getFormat("DDDD, MMMM, DD, YYYY"));
CellStyle numberStyle = application.getWorkbook().createCellStyle();
numberStyle.setDataFormat(dataFormat.getFormat("#,##0.00 \" Coins\""));
CellStyle[] columnCellStyles = new CellStyle[]{null, null, dateStyle, numberStyle, null};
boolean success = application.writeDataInSheet(data, columnCellTypes, columnCellStyles);
System.out.println(success);
if (success) {
success = application.writeExcelFile(fileName);
System.out.println(success);
if (success) {
success = application.openExcelFile(fileName);
System.out.println(success);
if (success) {
System.out.println("Done successfully");
}
}
}
}
}

Apache POI error message displayed for RETURN_BLANK_AS_NULL

I have code for witting data in Excel file whenever cell founds empty. However when i type below code it gives error. :
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
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.apache.poi.ss.usermodel.Row;
import Config.Constants;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row, xRow;
public static void setExcelFile(String Path, String SheetName) throws Exception {
// TODO Auto-generated method stub
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
// ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
public static String getCellData(int RowNum, int ColNum, String SheetName) throws Exception {
ExcelWSheet = ExcelWBook.getSheet(SheetName);
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static int getRowCount(String SheetName) {
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number = ExcelWSheet.getLastRowNum() + 1;
return number;
}
//This method is to get the Row number of the test case
//This methods takes three arguments(Test Case name , Column Number & Sheet name)
public static int getRowContains(String sTestCaseName, int colNum, String SheetName) throws Exception {
int i;
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int rowCount = ExcelUtils.getRowCount(SheetName);
for (i = 0; i < rowCount; i++) {
if (ExcelUtils.getCellData(i, colNum, SheetName).equalsIgnoreCase(sTestCaseName)) {
break;
}
}
return i;
}
//This method is to get the count of the test steps of test case
//This method takes three arguments (Sheet name, Test Case Id & Test case row number)
public static int getTestStepsCount(String SheetName, String sTestCaseID, int iTestCaseStart) throws Exception {
for (int i = iTestCaseStart; i <= ExcelUtils.getRowCount(SheetName); i++) {
if (!sTestCaseID.equals(ExcelUtils.getCellData(i, Constants.Col_TestCaseID, SheetName))) {
int number = i;
return number;
}
}
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number = ExcelWSheet.getLastRowNum() + 1;
return number;
}
#SuppressWarnings("static-access")
public static void setCellData(String Result, int RowNum, int ColNum, String SheetName) throws Exception {
try {
ExcelWSheet = ExcelWBook.getSheet(SheetName);
Row = ExcelWSheet.getRow(RowNum);
xRow = ExcelWSheet.getRow(RowNum);
// Row.RETURN_BLANK_AS_NULL;
// ExcelWBook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);
//Cell = Row.getCell(ColNum, Blank);
Cell = xRow.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData);
//ExcelWBook.write(fileOut);
ExcelWBook.write(fileOut);
//fileOut.flush();
fileOut.close();
ExcelWBook = new XSSFWorkbook(new FileInputStream(Constants.Path_TestData));
} catch (Exception e) {
DriverScript.bResult = false;
}
}
}
Error message:
MissingCellPolicy cannot be resolved or is not a field
Whereas when i use "Row.RETURN_BLANK_AS_NULL" it says method is deprecated. Can i have some solution for this both problems to run my code succesfully?
Cell has many types and you should get value according to its type, getStringCellValue() is not enough
I often use this code to get
switch (cell.getCellTypeEnum()) {
case FORMULA:
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellTypeEnum()) {
case BOOLEAN:
value = Boolean.toString(cellValue.getBooleanValue());
break;
case NUMERIC:
value = Double.toString(cellValue.getNumberValue());
break;
case STRING:
value = cellValue.getStringValue();
break;
}
break;
case BOOLEAN:
value = Boolean.toString(cell.getBooleanCellValue());
break;
case NUMERIC:
value = Double.toString(cell.getNumericCellValue());
break;
default:
value = cell.getStringCellValue();
break;
}

Unable to return the read the values present in an excel file

I want to return the values present in an excel file but it is returning values like [[Ljava.lang.String;#490ab905. Data is not returning the values like user name. Used jxl and data provider. Even i am not aware of data provider much. Please help me to fetch the accurate values from excel.
Following are my code:
public class excelUtil {
// public String suiteFileName = "/suite.xls";
String testDatafile = "/src/testData/testdata.xls";
// public String testDatafile = "/testdata/Testdata.xls";
#DataProvider
public Object[][] getTestData(String sheetName)
{
//String getTestData(String sheetName, int rowNumber, int colNum) {
// Read Excel
String path = System.getProperty("user.dir") + testDatafile;
Workbook w = null;
File inputWorkbook = new File(path);
// Open workbook
try {
w = Workbook.getWorkbook(inputWorkbook);
} catch (BiffException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the first sheet
Sheet sheet = w.getSheet(sheetName);
//Loop over first 10 column and lines
// Get the first sheet
//Loop over first 10 column and lines
int rowCount = sheet.getRows();
int columnCount = sheet.getColumns();
Object[][] data = new String[rowCount-1][columnCount];
for(int i=1;i<rowCount;i++)
{
Cell cell = sheet.getCell(0, i);
String value = cell.getContents().toString();
System.out.println(value);
data[i-1][0]= value.toString();
System.out.println(data[i-1][0]);
cell = sheet.getCell(1, i);
value = cell.getContents().toString();
data[i-1][1]= value.toString();
}
w.close();
//System.out.println(value);
System.out.println(data);
return data;
}
public static WebDriver driver ;
#Test(dataProvider = "getTestData")
public void OrpakLoginTest(Object username, Object password) {
driver = new FirefoxDriver();
driver.get("http:orpakqa.commdel.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Loginelements lg = new Loginelements();
WebElement element_UserName = lg.getOrpakUserNameField(driver);
element_UserName.sendKeys(username.toString());
WebElement element_Password = lg.getOrpakPasswordField(driver);
element_Password.sendKeys(password.toString());
//WebElement element_LoginBtn = lg.getOrpakLoginButton(driver);
//element_LoginBtn.click();
}
Use POI Jars
https://poi.apache.org/download.html
Below code is working for me:-
public String getXLcellValue(String xlpath, String sheetName, int rowNum, int cellNum)
{
try{
FileInputStream fis=new FileInputStream(xlpath);
Workbook wb=WorkbookFactory.create(fis);
Log.info("Get the value from the cell(getXLcellValue)");
return wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getStringCellValue();
}
catch(Exception ex)
{
Log.info("Error in getXLcellValue ="+ ex.getMessage());
}
return "";
}
xlpath = path of excel file in your system
Sheetname = name of the sheet in excel file
row = row number of username or password
cellnum = cell number of username or password
You can update your code as below and I hope this solution work for you:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ProApp extends OneClass {
Workbook wb;
Sheet sh1;
int numrow;
String username;
String password;
#BeforeMethod
public void oneTimeSetUp() throws InterruptedException {
driver.manage().window().maximize();
driver.get("Testing.com");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='app']/div/main/section/ul/li[1]/a")).click();
Thread.sleep(1000);
}
#Test(dataProvider="testdata")
public void testFireFox(String uname,String password1) throws InterruptedException
{
driver.findElement(By.xpath("//input[#name='username']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='username']")).sendKeys(uname);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password1);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#name='loginButton']")).click();
Thread.sleep(1000);
}
#DataProvider(name="testdata")
public Object[][] TestDataFeed(){
try {
// load workbook
wb=Workbook.getWorkbook(new File("C://File//Book2.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 [][] logindata=new Object[numrow][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0;i<numrow;i++){
// Fetch first row username
logindata[i][0]=sh1.getCell(0,i).getContents();
// Fetch first row password
logindata[i][1]=sh1.getCell(1,i).getContents();
}
// Return 2d array object so that test script can use the same
return logindata;
}
}

Read and write excel in Selenium WebDriver

I'm new to Selenium WebDriver and still learning. I just want to read the data from the excel and write the data either in a same excel sheet or different excel sheet.
User name and passwor for login is stored in excel sheet in two columns. I want to read the username/password from the excel sheet. If it's a valid user name/pwd I just wanted to Write "Pass" in new column else I need to write it as "Fail"
My code works successfully for reading data from excel sheet. However i'm stuck with writing data in excel sheet.
Thanks for reading and coming forward to clear my doubt.
Consider using Apache POI for reading and writing the excel. May be you can write a simple Util class which reads and writes excel .
To get the user id and password the util class should have a method to read excel and pass it to your selenium script.
Once the credentials are validated util class should have a method to write pass/fail to your excel.
Sample code to create row and write to a cell using POI
Sheet sheet = wb.createSheet("Selenium Results");
Row titleRow = sheet.createRow(0)
row = sheet.createRow(11);
cell = row.createCell(2);
cell.setCellValue("Total cost of loan");
Refer this Example
In your case you may just need to iterate the existing excel then read/write.
The following Selenium Java code using Apache POI should work:
public String readDataFromExcel(int rowcount,int columncount,String filepath,String Sheetname )
{
String data=null;
try
{
FileInputStream input= new FileInputStream(filepath);
XSSFWorkbook wb=new XSSFWorkbook(input);
XSSFSheet sh=wb.getSheet(Sheetname);
XSSFRow row=sh.getRow(rowcount);
row.getCell(columncount).toString();
}
catch(Exception e)
{
System.out.println(e);
}
return data;
}
public void writeDataFromExcel(int rowcount,int columncount,String filepath,String Sheetname,String value)
{
try
{
FileInputStream input=new FileInputStream(filepath);
XSSFWorkbook wb=new XSSFWorkbook(input);
XSSFSheet sh=wb.getSheet(Sheetname);
XSSFRow row=sh.getRow(rowcount);
FileOutputStream webdata=new FileOutputStream(filepath);
row.createCell(columncount).setCellValue(value);
wb.write(webdata);
}
catch(Exception e)
{
}
}
public class Xls_Reader
{
public String path="";
private Workbook workbook=null;
private Sheet sheet=null;
public Xls_Reader(String filePath)
{
path=filePath;
workbook=getWorkBook(path);
sheet=workbook.getSheetAt(0);
}
/**
* This function returns workbook object of excel file
* #param path is location of file in file System
* #return object of Type XSSFWorkbook
*/
public Workbook getWorkBook(String path)
{
Workbook workbook=null;
File file=new File(path);
if(file.exists())
{
try
{
FileInputStream input= new FileInputStream(path);
String extension=FilenameUtils.getExtension(path);
workbook= extension.equalsIgnoreCase("xls")?new HSSFWorkbook(input):new XSSFWorkbook(input);
input.close();
}
catch (IOException e)
{
throw new TARuntimeException(String.format("Problem While opening the file(%s)", path), e);
}
}
else
{
throw new NotFoundException(String.format("File(%s) is not exist..!!", path));
}
return workbook;
}
/**
* Depending upon sheet name it returns the sheet object
* #param sheetName is name of sheet
* #return if sheet exist returns XSSFSheet object else returns null.
*/
public Sheet getSheet(String sheetName)
{
if(workbook.getSheetName(workbook.getSheetIndex(sheet)).equals(sheetName))
{
return sheet;
}
if(sheetName==null || sheetName.isEmpty())
{
}
else
{
int index=workbook.getSheetIndex(sheetName);
if(index==-1)
{
throw new NotFoundException(String.format("Sheet(%s) is not found in Excel Workbook(%s)",sheetName,path));
}
else
{
sheet=workbook.getSheetAt(index);
}
}
return sheet;
}
/**
* Depending upon index it returns the sheet object
* #param index - is index of sheet
* #return if sheet exist returns XSSFSheet object else returns null.
*/
public Sheet getSheetAt(int index)
{
if(index<0)
{
throw new NotFoundException(String.format("Sheet is not found # index = %s", index));
}
else
{
sheet=workbook.getSheetAt(index);
}
return sheet;
}
/**
* This function returns cell contents as string
* #param sheetName name of the sheet
* #param columnNumber
* #param rowNumber
* #return returns cell contents as string
*/
public String getCellData(String sheetName,int rowNumber,int columnNumber)
{
String celldata="";
if(columnNumber>=0 || rowNumber >=0)
{
try
{
sheet=getSheet(sheetName);
Row row=sheet.getRow(rowNumber);
Cell cell= row.getCell(columnNumber);
celldata = getCellContentAsString(cell);
}
catch(NullPointerException e)
{
TALogger.logError("Geting NullPointerException while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber);
return "";
}
catch(Exception ex)
{
TALogger.logError("Geting exception while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber,ex);
return "";
}
}
else
{
throw new TARuntimeException("Invalid index..!! rowIndex= " + rowNumber +" columnIndex="+columnNumber);
}
return celldata;
}
/**
* This function returns cell contents as string
* #param sheetName
* #param columnName
* #param rowNumber
* #return returns cell contents as string
*/
public String getCellData(String sheetName,int rowNumber,String columnName)
{
String celldata="";
sheet=getSheet(sheetName);
int columnNumber=getColumnNumber(0, columnName);
if(columnNumber>=0 || rowNumber >=0)
{
try
{
Row row=sheet.getRow(rowNumber);
Cell cell= row.getCell(columnNumber);
celldata = getCellContentAsString(cell);
}
catch(NullPointerException e)
{
TALogger.logError("Geting NullPointerException while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber);
return "";
}
catch(Exception ex)
{
//This Log Error Should be here. Sometimes we get exception while reading the cell data if the cell is blank.
TALogger.logError("Geting exception while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber,ex);
return "";
}
}
else
{
throw new TARuntimeException("Invalid index..!! rowIndex= " + rowNumber +" columnIndex="+columnNumber);
}
return celldata;
}
public boolean setCellData(String sheetName,int rowNum,String colName,int headerColumnNumber, String data)
{
int columnNumber=getColumnNumber(headerColumnNumber, colName);
boolean result= setCellData(sheetName, rowNum, columnNumber, headerColumnNumber, data);
return result;
}
public boolean setCellData(String sheetName,int rowNum,int columnNum,int headerColumnNumber, String data)
{
try
{
sheet=getSheet(sheetName);
Row row=sheet.getRow(rowNum);
if(row==null)
row=sheet.createRow(rowNum);
sheet.autoSizeColumn(columnNum);
Cell cell=row.getCell(columnNum);
if(cell==null)
cell=row.createCell(columnNum);
cell.setCellValue(data);
writeToExcel(workbook, path);
}
catch(Exception e)
{
throw new TARuntimeException("Problem While setting data #rowNum="+rowNum+ " ColumnNum= "+columnNum,e);
}
return true;
}
/**
*
* #param rowNum
* #param columnName
* #return
*/
public int getColumnNumber(int rowNum, String columnName)
{
int colNum=-1;
if(rowNum>=0 && (!columnName.isEmpty()))
{
Row row=sheet.getRow(rowNum);
for(int i=0;i<row.getLastCellNum();i++)
{
Cell cell = null;
try
{
cell = row.getCell(i);
}
catch(NullPointerException e)
{
TALogger.logError(String.format("Cell number %s is not defined #rowNum = %s", i, rowNum));
}
if( cell != null && cell.getStringCellValue().trim().equalsIgnoreCase(columnName))
{
colNum=i;
break;
}
}
}
if(colNum==-1)
{
TALogger.logDebug("Enable to find column " + columnName + " at row number "+ rowNum);
}
return colNum;
}
/**
* This function returns the total number of column exist in sheet.
* This function consider the first row of the sheet as the column row
* #param sheetName is the name of the sheet
* #return returns the column count
*/
public int getColumnCount(String sheetName)
{
sheet = getSheet(sheetName);
Row row = sheet.getRow(0);
if(row==null)
return -1;
return row.getLastCellNum();
}
/**
* This function returns the total number of columns depending upon columnEndKeyWord.
* E.g It will increase the counter for the columns until it find the columnEndKeyWord in the passed rowNumber.
* MaxColumn count is 200 to avoid the infinite loop
* #param sheetName is the name of the sheet
* #return returns the column count
*/
public int getColumnCount(String sheetName,int rowNumber,String columnEndKeyWord)
{
int MaxColumnCount=200;
int columnCount=0;
int currentColumn=1;
while(currentColumn<=MaxColumnCount)
{
if(getCellData(sheetName,rowNumber,currentColumn).equalsIgnoreCase(columnEndKeyWord))
{
break;
}
else
{
columnCount=columnCount+1;
currentColumn=currentColumn+1;
}
}
return columnCount;
}
/**
*
* #param sheetName
* #return
*/
public int getRowCount(String sheetName)
{
sheet = getSheet(sheetName);
int number=sheet.getLastRowNum();
return number+1;
}
/**
*
* #param cell
* #return
*/
private String getCellContentAsString(Cell cell) throws Exception
{
String celldata="";
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BLANK:
celldata="";
break;
case Cell.CELL_TYPE_STRING:
celldata=cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
DataFormatter df=new DataFormatter();
celldata=df.formatCellValue(cell);
break;
case Cell.CELL_TYPE_FORMULA:
celldata=String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
celldata=String.valueOf(cell.getBooleanCellValue());
break;
default:
celldata=cell.getStringCellValue();
break;
}
return celldata;
}
public synchronized static void writeToExcel(Workbook workbook,String filePath)
{
FileOutputStream fileOut;
try
{
fileOut = new FileOutputStream(filePath);
workbook.write(fileOut);
fileOut.close();
}
catch (IOException e)
{
throw new TARuntimeException(String.format("Problem while writting into the file(%s)",filePath),e);
}
}
}
# Read data from excel in #selenium
package readdata;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
public class ReadURL {
public static WebDriver driver;
private static final String FILE_NAME = "Enter Excel path here;
#SuppressWarnings("unused")
private static final boolean String = false;
public static void main(String[] args) throws InterruptedException {
File file = new File(".\\driver\\geckodriver.exe");
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());
driver = new FirefoxDriver();
String URL = "URL HERE";
driver.get(URL);
System.out.println("URL ENTERED");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
#SuppressWarnings("resource")
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
// convert current cell into string because cell value can't enter into text box
String value = currentCell.getStringCellValue();
// System.out.println(value);
driver.findElement(By.id("enter_website_field")).sendKeys(value);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("starttest_butoon")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
try {
// This is special code to read pseudo element alert
String script = "return window.getComputedStyle(document.querySelector('.analyzer_search_inner.tooltipstered'),':after').getPropertyValue('content')";
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor) driver;
String content = (String) js.executeScript(script);
System.out.println(content);
if (content.contains("\"Enter url to analyze\"")) {
System.out.println("\nInvalid URL\n" + value);
}
} catch (JavascriptException e) {
System.out.println("\nValid URL\n" + value);
}
driver.findElement(By.id("enter_website_field")).clear();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources