Reading excel to list of Hashtable in Java - java

I have a code to read an excel file and place it in a list Hash tables. The code that I have is:
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ReadExcelTest {
public static Hashtable htable=new Hashtable();
public static List<Hashtable<String,String>> exceldata = new ArrayList<Hashtable<String,String>>();
public static void main() throws IOException{
readexcel(System.getProperty("user.dir")+"//src//config//TestData.xls");
}
#Test
public static void readexcel() throws IOException
{
String inputFile=System.getProperty("user.dir")+"//src//config//TestData.xls";
File inputWorkbook = new File(inputFile);
Workbook w;
Cell firstrowelement = null;
try
{
w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
for (int j = 0; j <sheet.getRows(); j++)
{
for (int i = 0; i < sheet.getColumns(); i++)
{
firstrowelement = sheet.getCell(i, 0);
Cell cell = sheet.getCell(i, j);
htable.put(firstrowelement.getContents(),cell.getContents());
System.out.print(firstrowelement.getContents()+"->"+cell.getContents());
}
System.out.println(firstrowelement.getContents());
exceldata.add(j,htable);
}
//printing the list
for(Hashtable hash :exceldata)
{
Enumeration e = hash.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + hash.get(key));
}
}
}
catch (BiffException e)
{
e.printStackTrace();
}
}
}
The output I am getting is all the hash tables in the list are displaying the same data instead of displaying each rows data.
Not exactly sure how to over come this issue. Any help is much appreciated.

You need to make a new htable for every row.
As it is, you keep re-using and updating a single HashTable.
(btw. prefer HashMap to HashTable).

Related

Error while using TestNg DataProvider must return either Object[][] or Iterator<Object>[], not class [[Ljava.lang.Object;

Testcase:
package Test;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Page.LoginPage;
import Utility.TestDataProvider;
import Utility.TestUtil;
//Testcase to perform login
public class LoginTest {
LoginPage page=new LoginPage();
#Test(dataProvider="ExcelDataProvider",dataProviderClass=TestDataProvider.class)
public void Logintest(String username,String password){
//page.login("user#phptravels.com","demouser");
page.login(username,password);
}
#AfterTest
public void TearDown(){
TestUtil.quit();
}
}
DataProvider:
package Utility;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestDataProvider {
static ExcelReader reader=new ExcelReader();
#DataProvider(name="ExcelDataProvider")
public static Object[][] ExcelDataProvider()
{
Object [][] rest = reader.readDataExcel("UserLogin");
return rest;
}
}
ExcelReader:
package Utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
static String fileName="Testdata";
public Object[][] readDataExcel(String TableName){
String filePath="F:\\TravelSite\\TravelSiteAutomation\\Testdata.xlsx";
File file =new File(filePath);
try{
FileInputStream stream=new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(stream);
XSSFSheet sheet=(XSSFSheet) workbook.getSheet("UnitTest");
List<XSSFTable> tables = sheet.getTables();
for(XSSFTable table:tables){
String name=table.getName();
if(name.equals(TableName)){
int ci=0,cj=0;
int rowNum=sheet.getLastRowNum()-sheet.getFirstRowNum();
//System.out.println(rowNum);
String[][] dataArray=new String[rowNum][100];
for(int i = 1; i < rowNum+1; i++) {
Row row = sheet.getRow(i);
//Create a loop to print cell values in a row
int colNum=row.getLastCellNum();
// System.out.println(colNum);
for(int j = 0; j <colNum; j++) {
//Print excel data in console
Cell cell=row.getCell(j);
DataFormatter formatter = new DataFormatter();
String var_name = formatter.formatCellValue(cell);
System.out.print(var_name+" || ");
dataArray[ci][cj]=var_name;
}
System.out.println();
}
workbook.close();
return dataArray;
}
}
Log.info("Table name is incorrect");
return null;
}
catch(Exception e)
{
Log.debug(e.getMessage());
return null;
}
}
}
so when i try to run the testcase i get an error
org.testng.TestNGException:
Data Provider public static java.lang.Object[][]
Utility.TestDataProvider.ExcelDataProvider() must return either
Object[][] or Iterator[], not class [[Ljava.lang.Object;
Nothing seems to resolve it,POI version 3.15, TestNGversion 6.10
The problem is with the ExcelReader class. Please find below the fixed version of the same which should solve the problem
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.ArrayList;
import java.util.List;
public class ExcelReader {
public static String[][] readDataExcel(String TableName) {
String filePath = "src/test/resources/Testdata.xlsx";
try {
Workbook workbook = new XSSFWorkbook(filePath);
XSSFSheet sheet = (XSSFSheet) workbook.getSheet("UnitTest");
List<XSSFTable> tables = sheet.getTables();
for (XSSFTable table : tables) {
String name = table.getName();
if (! name.equals(TableName)) {
continue;
}
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
System.out.println(rowCount);
int columnCount = - 1;
List<List<String>> data = new ArrayList<>();
for (int i = 1; i < rowCount + 1; i++) {
Row row = sheet.getRow(i);
int colNum = row.getLastCellNum();
if (columnCount == - 1) {
columnCount = colNum;
}
List<String> rowData = new ArrayList<>();
for (int j = 0; j < colNum; j++) {
Cell cell = row.getCell(j);
DataFormatter formatter = new DataFormatter();
String var_name = formatter.formatCellValue(cell);
if (var_name != null && ! var_name.trim().isEmpty()) {
rowData.add(var_name);
}
}
if (! rowData.isEmpty()) {
data.add(rowData);
}
}
workbook.close();
String[][] dataArray = new String[rowCount-1][columnCount];
int rowIndex = 0;
for (List<String> row : data) {
int colIndex = 0;
for (String rowData : row) {
dataArray[rowIndex][colIndex++] = rowData;
}
rowIndex++;
}
return dataArray;
}
System.err.println("Table name is incorrect");
return new String[][] {{}};
} catch (Exception e) {
e.printStackTrace();
return new String[][] {{}};
}
}
}

Selenium/Java-How to make 'dataProvider' a common function inbetween multiple source folders

I have created a project with seperate source folder for each module, say mod1 & mod2 and the src source folder as common for each source folder.
And I created DataProvider_Repository.java file for reading data from excel sheet. Which now I need to put Data Provider in each source folder for accessing it in each testcase(Eg:Registration.java or Del.java).
How can I make it common & put in src folder.
DataProvider_Repository.java contains same code for reading data from excel sheet.
DataProvider_Repository.java
package online;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
public class DataProvider_Repository {
#DataProvider(name="dataProviderRepo")
public static Object[][] getDataFromDataprovider(Method m) throws IOException{
Object[][] object = null;
String filePath = System.getProperty("user.dir")+"\\";
String fileName = "sample.xlsx";
String sheetName= "sampleSheet";
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(inputStream);
Sheet s = wb.getSheet(sheetName);
//Find number of rows in excel file
int rowCount = s.getLastRowNum()-s.getFirstRowNum();
object = new Object[rowCount][6];
for (int i = 0; i < rowCount; i++) {
//Loop over all the rows
Row row = s.getRow(i+1);
int lst = row.getLastCellNum();
//Create a loop to print cell values in a row
for (int j = 0; j < lst; j++) {
//Print excel data in console
if(row.getCell(j) != null){
object[i][j] = row.getCell(j).toString();
}
}
object[i][lst-1] = Integer.toString(i);
}
return object;
}
}
Registration.java
package online;
import org.testng.annotations.Test;
public class Registration {
#Test(dataProviderClass=DataProvider_Repository.class,dataProvider="dataProviderRepo")
public void OnlineRegs(String testcaseName,String keyword,String objectName,String objectType,String value, String rowNum) throws Exception {
System.out.println("=======OnlineReg===========");
//Operations here...
}
}
The folder structure is

insert data stored in array list in excel using java

Its been a while i m trying to create a excel sheet to store the crawled data in a table format in a excel , the data is fetched from a url and stored in a array list , this data is needed to be stored in a array list `
import java.util.ArrayList;
import com.webscrap4j.WebScrap;
import com.webscrap4j.WebScrapException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFTable;
public class crawl
{
public static void main(String[] args) throws IOException {
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> bl = new ArrayList<String>();
ArrayList<String> cl = new ArrayList<String>();
WebScrap ws = new WebScrap();
ws.setUrl("https://www.pepperfry.com/hardware-electricals-power-storage-ups-inverters.html");
try
{
ws.startWebScrap();
//al = ws.getImageTagData("img", "title");
al = ws.getSingleHTMLScriptData("<div class='card-body-title hidden-txt'>", "</div>");
bl = ws.getSingleHTMLScriptData("<span class='strike'>", "</span>");
cl = ws.getSingleHTMLScriptData("<p class='card-body-price txt-red'>", "</p>");
/* FileOutputStream fos=new FileOutputStream("/Users/parthpatil/Documents/11.xls");
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet Sheet = workBook.createSheet("products");
//XSSFTable my_table = Sheet.createTable();
HSSFRow row;
HSSFCell cell;
CreationHelper helper = workBook.getCreationHelper();
Row header = Sheet.createRow(0);
header.createCell(0).setCellValue("Product Name");
header.createCell(1).setCellValue("Product Price");
header.createCell(2).setCellValue("Product MRP");
for(int i=0;i<al.size();i++){
row = Sheet.createRow((short) i);
cell = row.createCell(i);
System.out.println(al.get(i));
cell.setCellValue(al.get(i).toString());
}
System.out.println("Done");
workBook.write(fos);
*/
for (String adata : al)
{
System.out.println("the product are:- " + adata);
}
for (String bdata : bl)
{
System.out.println("the MRp are:- " + bdata);
}
for (String cdata : cl)
{
System.out.println("the selling price is:- " + cdata);
}
} catch (WebScrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your code is globally correct it has only some little mistakes, here is how it could be done with your code:
// Use the try-with-resource statement to close all the resources properly
try (HSSFWorkbook workBook = new HSSFWorkbook();
FileOutputStream fos = new FileOutputStream("/Users/parthpatil/Documents/11.xls")) {
// Create the Sheet
HSSFSheet Sheet = workBook.createSheet("products");
// Create the first row corresponding to the header
Row header = Sheet.createRow(0);
header.createCell(0).setCellValue("Product Name");
header.createCell(1).setCellValue("Product Price");
header.createCell(2).setCellValue("Product MRP");
// Ensure that all the List have the same size otherwise throw an exception
if (al.size() != bl.size() || al.size() != cl.size())
throw new IllegalStateException("Some data is missing");
// Iterate over all the list an create the rows of data
for(int i = 0; i < al.size(); i++){
// Create the current starting from 1 to al.size()
HSSFRow row = Sheet.createRow((short) i + 1);
// Cell of the Product Name
row.createCell(0).setCellValue(al.get(i));
// Cell of the Product Price
row.createCell(1).setCellValue(cl.get(i));
// Cell of the Product MRP
row.createCell(2).setCellValue(bl.get(i));
}
// Write the result into the file
workBook.write(fos);
}

Java error message => is undefined for the type -when creating an object from different package

I have the following code where I am calling a class from another package and I get:
undefined for the type
Package A:
import Excel.WriteExcel;
public void setupAfterSuite() {
WriteExcel x = new WriteExcel();
**x.WriteResults(testresultdata, sheet, workbook);**
Getting the following error:
The method WriteResults(Map, HSSFSheet, HSSFWorkbook)
is undefined for the type WriteExcel
Package B:
public void WriteResults(Map<String, Object[]> testresultdata1, HSSFSheet readsheet1, HSSFWorkbook workbook1) {
// TODO Auto-generated method stub
Set<String> keyset = testresultdata1.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = readsheet1.createRow(rownum++);
Object [] objArr = testresultdata1.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
readsheet1.autoSizeColumn(rownum);
for(int i=rownum; i>0; i--){
readsheet1.autoSizeColumn(i);
}
It's probably something minor. Can anyone please advise.
Thanks
You are not sharing some important information, so don't be surprised no-one helped you...
Let me try the same, what you are saying you did.
You didn't share first class name and package name, so I named it ClassA and is defined in q34201803.a package:
package q34201803.a;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import Excel.WriteExcel;
public class ClassA {
public void setupAfterSuite() {
WriteExcel x = new WriteExcel();
HSSFSheet sheet = null;
HSSFWorkbook workbook = null;
Map<String, Object[]> testresultdata;
testresultdata = new LinkedHashMap<String, Object[]>();
x.WriteResults(testresultdata, sheet, workbook);
}
}
Then I created second class based on import in your code:
package Excel;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class WriteExcel {
public void WriteResults(Map<String, Object[]> testresultdata1, HSSFSheet readsheet1, HSSFWorkbook workbook1) {
// not important...
}
}
and it works fine for me.
Please share full source code of your classes I think, there might be problem in imports.
Also you should learn Java naming conventions if you want to code in Java.
Sorry I am new to Coding
**Here is all of the code:**
package Excel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class WriteExcel {
public void WriteResults(Map<String, Object[]> testresultdata1, HSSFSheet readsheet1, HSSFWorkbook workbook1) {
// TODO Auto-generated method stub
Set<String> keyset = testresultdata1.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = readsheet1.createRow(rownum++);
Object [] objArr = testresultdata1.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
readsheet1.autoSizeColumn(rownum);
for(int i=rownum; i>0; i--){
readsheet1.autoSizeColumn(i);
}
try {
File dir = new File("Results");
dir.mkdir();
FileOutputStream out =new FileOutputStream(new File("Results/TestResult.xls"));
workbook1.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
**This is the second Class:**
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.testng.ITestContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Excel.WriteExcel;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class UserSettingTest {
//define an Excel Work Book
HSSFWorkbook workbook;
//define an Excel Work sheet
HSSFSheet sheet;
//define a test result data object
Map<String, Object[]> testresultdata;
//define an Excel Work Book
HSSFWorkbook workbookRead;
//define an Excel Work sheet
HSSFSheet Readsheet;
#BeforeClass(alwaysRun = true)
public void setupBeforeSuite(ITestContext context) {
//create a new work book
workbook = new HSSFWorkbook();
//create a new work sheet
//sheet = workbook.createSheet("Test Result");
testresultdata = new LinkedHashMap<String, Object[]>();
//add test result excel file column header
//write the header in the first row
testresultdata.put("1", new Object[] {"Test Step Id", "Action", "Expected Result","Actual Result"});
}
#DataProvider(name = "DP1")
public Object[][] createData1() throws BiffException, IOException
{
Object[][] retObjArr=getTableArray("data1.xls", "DataPool", "imdbTestData1" );
return (retObjArr);
}
#SuppressWarnings("unused")
private Object[][] getTableArray(String xlFilePath, String SheetName, String tableName) throws BiffException, IOException {
String[][] tabArray=null;
Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
jxl.Sheet sheet = workbook.getSheet(SheetName);
int startRow,startCol, endRow, endCol,ci,cj;
jxl.Cell tableStart=sheet.findCell(tableName);
startRow=tableStart.getRow();
startCol=tableStart.getColumn();
jxl.Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false);
endRow=tableEnd.getRow();
endCol=tableEnd.getColumn();
System.out.println("startRow="+startRow+", endRow="+endRow+", " +
"startCol="+startCol+", endCol="+endCol);
tabArray=new String[endRow-startRow-1][endCol-startCol-1];
ci=0;
for (int i=startRow+1;i<endRow;i++,ci++){
cj=0;
for (int j=startCol+1;j<endCol;j++,cj++){
tabArray[ci][cj]=sheet.getCell(j,i).getContents();
}
}
return(tabArray);
}
int RowNo =3;
int testCase=1;
#Test
public void testDataProviderExample(String movieTitle,
String directorName, String moviePlot, String actorName) throws Exception {
//start
String SRowNo = "" + RowNo;
String StestCase = "TC"+ testCase ;
System.out.println("DirectorName is: "+directorName);
System.out.println("DirectorName is: "+moviePlot);
System.out.println("DirectorName is: "+actorName);
testresultdata.put(SRowNo, new Object[] {StestCase,directorName, "Logged Out","Fail"});
RowNo++;
testCase++;
}
#AfterClass
public void setupAfterSuite() {
WriteExcel x = new WriteExcel();
x.WriteResults(testresultdata, Readsheet, workbook);
try {
File dir = new File("Results");
dir.mkdir();
FileOutputStream out =new FileOutputStream(new File("Results/TestResult.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
**When i run i get the following**
[TestNG] Running:
C:\Users\xxxxx\AppData\Local\Temp\testng-eclipse-859939429\testng-customsuite.xml
FAILED CONFIGURATION: #AfterClass setupAfterSuite
java.lang.NullPointerException
at Excel.WriteExcel.WriteResults(WriteExcel.java:26)
at test.UserSettingTest.setupAfterSuite(UserSettingTest.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:220)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:773)
at org.testng.TestRunner.run(TestRunner.java:623)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
at org.testng.SuiteRunner.run(SuiteRunner.java:259)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
at org.testng.TestNG.run(TestNG.java:1018)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Line 26 referring to: ===> Row row = readsheet1.createRow(rownum++);
You didn't initialize the Readsheet object. This way, you're passing a null argument to WriteResults method.
x.WriteResults(testresultdata, Readsheet, workbook);
That causes NullPointerException at this line.
Row row = readsheet1.createRow(rownum++);
readsheet1 is null.

Error calling a java class (Selenium WebDriver, TestNG)

I'm trying to create a java class for reading an excel file. I want to use it in Selenium WebDriver (using Eclipse IDE) to do test driven scripts.
I have one line that stumps me:
//error here---->>>>Object[][] retObjArr = data("C:\ExcelFiles\LoginData.xls");
This line is generating an error "The method data(String) is undefined for the type Login"
I'm fairly new to OOP but thought I could call the class ExcelRead like the above and pass in one arg string...but obviously not!
I'm sure many of you know how TestNG DataProviders annotations work which is what I'm trying to do here. There are many examples of this but all of them pull the ExcelRead code into the main TestNG project (Login in this case) class. I thought I'd make the excelRead class a separate class file that I could just call from any test class I create in the future.
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Login {
#DataProvider(name = "ExcelInput")
public Object[][] createData() throws Exception{
ExcelRead data = new ExcelRead();
//error here---->>>>Object[][] retObjArr = data("C:\ExcelFiles\LoginData.xls");
return(retObjArr);
}
#Test(dataProvider = "ExcelInput")
public void LoginTest(String Username, String Password) throws InterruptedException{
System.out.println("test");
}
}
// code in its own Class file
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelRead {
public static Object[][] main( String[] args) throws Exception{
File excel = new File(args[1]);
FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Input") ;
int rowNum = ws.getLastRowNum() + 1 ;
int colNum = ws.getRow(0).getLastCellNum() ;
String[][] data = new String[rowNum][colNum] ;
for ( int i = 0 ; i < rowNum ; i++) {
HSSFRow row = ws.getRow(i) ;
for ( int j = 0 ; j < colNum ; j++) {
HSSFCell cell = row.getCell(j) ;
String value = cellToString(cell);
data[i][j] = value ;
System.out.println("the value is " + value);
}
}
return data;
}
public static String cellToString(HSSFCell cell) {
int type ;
Object result ;
type = cell.getCellType() ;
switch (type) {
case 0 : // numeric value in Excel
result = cell.getNumericCellValue() ;
break ;
case 1 : // String Value in Excel
result = cell.getStringCellValue() ;
break ;
default :
throw new RuntimeException("There are no support for this type of cell") ;
}
return result.toString() ;
}
}
Try this:
Object[][] retObjArr = data.fileRead("C:\ExcelFiles\LoginData.xls");
Modify main as follows:
Change main to fileRead
public static Object[][] fileRead( String args) throws Exception{
File excel = new File(args);

Categories

Resources