Testng:Dataprovider: error : sun.reflect.NativeMethodAccessorImpl#2f1ea80d - java

I am trying to read data from excel which contains only one column with three rows in it
ID
A1002
B1003
C1004
I am using dataprovider in Testng to achieve the same. But on returning the 2D Object array, I am getting sun.reflect.NativeMethodAccessorImpl#2f1ea80d error
#DataProvider(name = "getLoginData")
public Object[][] LoginData() throws Exception
{
Workbook workbook = null;
ArrayList<String> values = new ArrayList<String>();
FileInputStream ExcelFile = new FileInputStream(Path_TestData);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(Home.sheetname);
int rows = ExcelWSheet.getPhysicalNumberOfRows();
System.out.println("Rows is" +rows);
for(int i=1; i<rows; i++)
{
XSSFRow row = ExcelWSheet.getRow(i);
values.add(row.getCell(0).getStringCellValue());
}
System.out.println("value size is" +values.size());
Object[][] returnValue = new Object[10][10];
for(i=0; i<values.size();i++)
{
returnValue[i][0] = values.get(i);
}
return returnValue;
}
#Test(dataProvider="getLoginData")
public void LoginData(String ID)
{
driver.findElement(By.xpath("//*[text()='select']")).click();
//clicking on the ID selected in dropdown
driver.findElement(By.xpath("//*[text()=ID]")).click();
}

Try following code, I've made few adjustments here and there:
#DataProvider(name = "getLoginData")
public static Object[][] LoginData() throws Exception
{
XSSFWorkbook ExcelWBook = null;
ArrayList<String> values = new ArrayList<String>();
FileInputStream ExcelFile = new FileInputStream("C:\\Users\\kushal8\\Desktop\\K1.xlsx");
ExcelWBook = new XSSFWorkbook(ExcelFile);
XSSFSheet ExcelWSheet = ExcelWBook.getSheet("Sheet1");
int rows = ExcelWSheet.getPhysicalNumberOfRows();
System.out.println("Rows is" +rows);
for(int i=1; i<rows; i++)
{
XSSFRow row = ExcelWSheet.getRow(i);
values.add(row.getCell(0).getStringCellValue());
}
System.out.println("value size is" +values.size());
Object[][] returnValue = new Object[15][15];
for(int i=0; i<values.size();i++)
{
returnValue[i][0] = values.get(i);
//System.out.println(returnValue[i][0]);
}
return returnValue;
}

Related

how to write array object content in excel through selenium

int col = driver.findElements(By.xpath("//table[#id=\"transactionListData\"]/thead/tr/th")).size();
int row =driver.findElements(By.xpath("//table[#id=\"transactionListData\"]/tbody/tr")).size();
//ArrayList<Object[]> mydata = new ArrayList<Object[]>();
Object [][] ob = new Object[row][col];
for( int i=1; i<=row; i++)
{
for (int j=1; j<=col; j++)
{
String text =driver.findElement(By.xpath("//*[#id='transactionListData']/tbody/tr["+i+"]/td["+j+"]")).getText();
//System.out.println("text " +text);
ob[i][j] = text;
}
}
try {
String s = util.writeIntoExcel(ob, row, col);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return flag;
}
I have passed ob in below function to write its content in to excel file. but unable to print where ob is a object array Object [][] ob = new Object[row][col];. I am getting an error where i am trying to write data in to excel regarding Object in to string conversion.
public static String writeIntoExcel(Object ob, int rowi,int colj ) throws IOException
{
int rowcount = rowi;
int colcount = colj;
Object oa[][] = new Object[rowcount][colcount];
oa = (Object[][]) ob;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Transacton History");
for (int i=1; i<=rowcount ; i++)
{
for (int j=1; j<=colcount ; j++)
{
String val = (String) oa[i][j];
Row row = sheet.createRow(i);
row.createCell(colj).setCellValue(val);
}
}
FileOutputStream fileOut = new FileOutputStream("\"\\\\btfin.com\\filesrv\\User\\Offshore\\SG1\\L097117\\user\\My Documents\\workbook.xlsx");
workbook.write(fileOut);
fileOut.close();
return "Data is written";
}
}
Answer to question above is :
Object [][] ob = new Object[row][col];
for( int i=1; i<=row; i++)
{
for (int j=1; j<=col; j++)
{
String text =driver.findElement(By.xpath("//*[#id='transactionListData']/tbody/tr["+i+"]/td["+j+"]")).getText();
//System.out.println("text " +text);
ob[i-1][j-1] = text;
}
}
// rest everything is fine..
public static String writeIntoExcel(Object[][] sob ) throws IOException
{
//String oa[][] = sob;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Transacton History");
Object cellvalue = null;
for (int i=0; i<=sob.length ; i++)
{
Row row = sheet.createRow(i + 1);
for (int j=0; j<=sob[i].length ; j++)
{
Cell cell=row.createCell(j+1);
cellvalue = sob[i][j];
if (cellvalue instanceof String)
cell.setCellValue((String)(cellvalue));
else if (cellvalue instanceof Integer)
cell.setCellValue((Integer)cellvalue);
cell.setCellValue((String)cellvalue);
}
}
FileOutputStream fileOut = new FileOutputStream("");
workbook.write(fileOut);
fileOut.close();
workbook.close();
return "Data is written";

Selenium reading data from Excel file

I am trying to read some test data from an Excel file (3 rows and 2 columns with no blank row in between) but in the output I am getting just the first row of the Excel. After that it is giving me a null pointer exception.
public class ReadDataFromExcel {
public void readExcel(String filePath,String fileName,String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook myWorkbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")) {
myWorkbook = new XSSFWorkbook(inputStream);
}
else if(fileExtensionName.equals(".xls")) {
myWorkbook = new HSSFWorkbook(inputStream);
}
Sheet mySheet = myWorkbook.getSheet(sheetName);
int rowCount = mySheet.getLastRowNum()- guru99Sheet.getFirstRowNum();
System.out.println("Total rows= " +rowCount);
for (int i = 0; i < rowCount+1; i++) {
Row row = mySheet.getRow(i);
int columnCount = row.getLastCellNum() - row.getFirstCellNum();
for(int j=0; j <= columnCount; j++) {
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
System.out.println();
}
}
public static void main(String...strings) throws IOException {
ReadDataFromExcel objExcelFile = new ReadDataFromExcel();
String filePath = System.getProperty("user.dir")+"\\src\\testFileInputOutput";
objExcelFile.readExcel(filePath,"testExcel.xlsx","testSheet");
}
}
I am getting the exception on this line:
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
To get past NullPointerException you can check for null by replacing the line that is throwing the exception with this:
Cell cell = row.getCell(j);
if (cell != null) {
System.out.print(cell.getStringCellValue());
}
System.out.print("|| ");

getting data by column name apache poi excel

I am using apache POI for excel import and parsing .
I have to get the data by passing column name .
this is my code
JSONObject jo = new JSONObject();
JSONArray dataCollection = new JSONArray();
JSONObject data = null;
try {
String tempCampaignFilesPath = getSessionData("userPath") + System.getProperty("file.separator") + "tempCampaignFiles";
File someFile = new File(tempCampaignFilesPath, fileName);
/* read from this file */
FileInputStream fileInputStream = new FileInputStream(someFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum() + 1;
int colNum = sheet.getRow(0).getLastCellNum();
Row row = null;
Cell cell = null;
for (int i = 1; i < rowNum; i++) {
row = sheet.getRow(i);
data = new JSONObject();
for (int j = 0; j < colNum; j++) {
cell = row.getCell(j);
data.put(columnList.get(j), cellToString(cell));
}
dataCollection.put(data);
}
fileInputStream.close();
// someFile.delete();
jo.put("tableData", dataCollection);
} catch (Exception e) {
e.printStackTrace();
}
return jo;
There is a provision for column index but how could I do it by column name.
Please help me.
You have to convert column name to index:
int colIdx = CellReference.convertColStringToIndex(letter);
CellUtil.getCell(row, colIdx)
or if you need convert column index to string:
String colName = CellReference.convertNumToColString(colIdx)
Please find below the code an another workaround for this .Please see the comments in code to be more clear what I have done.
JSONObject jo = new JSONObject();
JSONArray dataCollection = new JSONArray();
JSONObject data = null;
try {
String tempCampaignFilesPath = getSessionData("userPath") + System.getProperty("file.separator") + "tempCampaignFiles";
File someFile = new File(tempCampaignFilesPath, fileName);
/* read from this file */
FileInputStream fileInputStream = new FileInputStream(someFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum() + 1;
int colNum = sheet.getRow(0).getLastCellNum();
Row row = null;
Cell cell = null;
/* first row data for column names and index */
Map<String, Integer> colMapByName = new HashMap<String, Integer>();
if (sheet.getRow(0).cellIterator().hasNext()) {
for (int j = 0; j < colNum; j++) {
colMapByName.put(cellToString(sheet.getRow(0).getCell(j)), j);
}
}
System.out.println(colMapByName);//shows the indexes of columns populated by traversing first row
/* first row data */
for (int i = 1; i < rowNum; i++) {
row = sheet.getRow(i);
data = new JSONObject();
//colMap consists the columnnames and alias name for it
for (Entry<String, String> colData : colMap.entrySet()) {
cell = row.getCell(colMapByName.get(colData.getValue()));//gives the index of column from colMapByName Map by passing column name
data.put(colData.getKey(), cellToString(cell));//now the data passed to the alias for the column tobe used in application
}
dataCollection.put(data);
}
fileInputStream.close();
someFile.delete();
jo.put("tableData", dataCollection);
} catch (Exception e) {
e.printStackTrace();
}
return jo;

Apache POI append data to excel sheet not working

I am reading data from an arraylist and writing this to an excel sheet. The problem is my excel is getting overwritten each time. Here is my code. I can't figure out what is wrong here :( Can someone please help?
public static void main( String[] args ) throws Exception
{
List<String> fileData = new ArrayList<String>();
for(File file:files) {
fileData.add(readFileContents(file.getAbsolutePath()));
}
for(String fileContent:fileData) {
//do some stuff that in turn calls the writeDataToExcel method
}
}
private static void writeDataToExcel(String test,Map<String,String> dataMap,Object object) throws IOException {
File file = new File("input/data.xls");
Map<String,Object[]> data = new LinkedHashMap<String,Object[]>();
XSSFWorkbook workbook = null;
int count = 0;
XSSFSheet sheet = null;
if(file.exists()) {
workbook = new XSSFWorkbook(new FileInputStream(file));
sheet = workbook.getSheet("Data Sheet");
}
else {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Data Sheet");
//count = sheet.getLastRowNum();
}
data.put("1", new Object[]{"Id","Name","Field","Description","Value"});
for(Map.Entry<String, String> dataMp:dataMap.entrySet()) {
data.put(Integer.toString(count+2), new Object[]{id,object.getClass().getSimpleName(),dataMp.getKey(),dataMp.getValue(),"null"});
count++;
}
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof String)
cell.setCellValue((String)obj);
}
}
FileOutputStream fis = new FileOutputStream("input/data.xls");
workbook.write(fis);
if(fis!=null)
fis.close();
}
I think problem is at line
int rownum = 0;
this will set rowNUm to zero each time and sheet will be written from zero row
You need to persist this rowNum value if you want to append data in the sheet

How to get the HSSFCell string value to List<String>>

I have created a method to pull the first row and another method to pull the test data. I am unable to add the cell directly to List using list.add(), how to convert them to string and add to list
public class read {
HSSFCell cell;
HSSFRow row;
HSSFWorkbook wbk;
HSSFSheet sheet;
List<HSSFCell> cellTempList;
Hashtable<String, String>[] data = null;
Iterator CIterator;
List<List<HSSFCell>> list;
HSSFFormulaEvaluator HFE = new HSSFFormulaEvaluator(wbk);
#SuppressWarnings("unchecked")
public String[] readFirstRow() throws IOException{
InputStream ipstream = new FileInputStream(new File("C:\readfile.xls"));
wbk = new HSSFWorkbook(ipstream);
sheet = wbk.getSheetAt(0);
row = sheet.getRow(0);
int numberofCells = row.getPhysicalNumberOfCells();
Object result;
String[] firstRow = new String[numberofCells];
for(int i = 0; i<= numberofCells; i++){
CIterator = row.cellIterator();
while(CIterator.hasNext()){
CIterator.next();
HSSFCell cellFirstRow = row.getCell(i);
switch(cellFirstRow.getCellType()){
case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
}
for(int j=0; j<=numberofCells; j++){
firstRow[i] = result.toString();
}
}
return firstRow;
}
public void getNextRow(){
Object obj;
list = new ArrayList<List<HSSFCell>>();
cellTempList = new ArrayList<HSSFCell>();
HSSFRow rowNext = sheet.getRow(1);
Iterator rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
rowIterator.next();
CIterator = rowNext.cellIterator();
for(int j = 0; j<= rowNext.getPhysicalNumberOfCells();j++){
while (CIterator.hasNext()) {
CIterator.next();
//HSSFCell cell = rowNext.getCell(numberofCells);
cellTempList.add(cell);
}
list.add(cellTempList);
}
}
}
If your cell contains String value, you can get it with ..
String value = cell.getRichStringCellValue().getString();
.. and then add it to a List<String> object

Categories