Nullpointer Exception While Using Trying to Read Excel in Selenium - java

Hi guys i Searched Every Where Solution For But Can't Find. Why Am Getting Null Pointer Exception For This i Dunno. Please Sort Me This Out. It is Showing as Path is Only Wrong But i Specified it Correctly only.
My Code :
package UsingExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.sun.rowset.internal.Row;
public class Demo
{
public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
{
File file = new File(filepath); // line 21
FileInputStream stream = new FileInputStream(file);
Workbook Mybook = null;
String FileExtensionnname = filename.substring(filename.indexOf("."));
if(FileExtensionnname.equals(".xlsx"))
{
Mybook = new XSSFWorkbook(stream);
}
else if(FileExtensionnname.equals(".xls"))
{
Mybook = new HSSFWorkbook(stream);
}
Sheet filesheet = Mybook.getSheet(Sheetname);
int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();
for(int i=0;i<rowcount+1;i++)
{
org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++)
{
System.out.println(row.getCell(j).getStringCellValue()+ "||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
Demo excelfile = new Demo();
String filepath = System.getProperty("E:\\Mybook.xlsx");
excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
}
}
My Error is :
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at UsingExcel.Demo.ReadExcel(Demo.java:21)
at UsingExcel.Demo.main(Demo.java:61)
Hope You Have Understood My Problem, Please Sort This out. But When am Testing a Login Page Using Excel That No Problem Will Be Coming, Now i Try To Print on The
Console it is Not Working.

Your filepath should just be
String filepath = "E:\\Mybook.xlsx", don't use System.getProperty.
From docs :
Gets the system property indicated by the specified key
A null is being passed to your method ReadExcel(...), because there is no System property defined as E:\Mybook.xlsx

Related

Can not write to excel file using JexcelAPI

import java.io.File;
import java.io.IOException;
import jxl.*;
import jxl.write.*;
import jxl.write.Number.*;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class reader {
public static void main(String args[]) throws IOException, WriteException, BiffException {
String inputFile = "C:\\Users\\Chemeris\\Documents\\Book1.xls";
File inputWorkbook = new File(inputFile);
Workbook w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
//Ading a label
Label label = new Label(2,2, "Hello");
sheet.addCell(label);
w.write();
w.close();
}
}
I get a cannot find symbol error on ".addCell" and on ".write".
If you can help me solve this problem or offer another solution to wrting to an existing excel file I would be most thankfull
You may try to use ApachePOI to get the same result. There are bunch of documents https://www.tutorialspoint.com/apache_poi/)

folder and file creation not working

I am currently having trouble creating a folder and a file if not present. I keep getting and error about it not being specified and I don't really know how to fix it.
this is my main
import java.io.IOException;
public class main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
timeKeepHome ja = new timeKeepHome();
//ja.setVisible(true);
fileTimeLog log = new fileTimeLog();
log.checkFile();
}
}
and this is my class to create the file/ folder.
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Formatter;
public class fileTimeLog
{
File log = new File("log/sixWeek.dat");
File folder = new File("log");
PrintWriter logW = new PrintWriter("log/sixWeek.dat");
public fileTimeLog() throws IOException
{
System.out.println("successful");
checkFile();
}
public void checkFile() throws IOException
{
if(!(log.exists()))
{
createFile();
}
}
public void saveTime() throws IOException
{
}
public void saveDate()
{
}
public void createFile() throws IOException
{
folder.mkdir();
logW = new PrintWriter(log);
logW.println("DONT MODIFY THIS FILE IF UNLESS YOU KNOW WHAT YOUR ARE DOING ");
logW.close();
}
}
and the error i'm getting
Exception in thread "main" java.io.FileNotFoundException: log\sixWeek.dat (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at java.io.PrintWriter.<init>(PrintWriter.java:184)
at fileTimeLog.<init>(fileTimeLog.java:17)
at main.main(main.java:18)
I would make everything look nicer and neater but I'm just really frustrated and I've done research but don't really understand.
The Printwriter will try and create a file, so when you do this
PrintWriter logW = new PrintWriter("log/sixWeek.dat");
in your class defintion, then it will try to create it, but the folder does not exist until you do createFile
As you re-initialize logW in createFile anyway, you do not need to initialize it in your class defintion

Argument type mismatch in JUnit

I'm fairly new to Selenium webdriver and Java, previously I used Selenium IDE. I'm trying to read testdata from an Excel sheet. Which is then written to Eclipse console, which works, and should be used to execute the actual test, which doesn't work. The actual test is not executed because I get an error argument type mismatch. The code looks like this:
package Test_Excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
#RunWith(Parameterized.class)
public class TestWithExcelData {
// Our two parameters
private final int input;
private final int resultExpected;
// Constructor
public TestWithExcelData(int input, int result) {
this.input = input;
this.resultExpected = result;
}
#Parameters
public static Iterable<Object []> data() throws BiffException, IOException
{
String FilePath = "C://Selenium//workspace//testproject//src//testdata//TestData.xls";
FileInputStream fs = new FileInputStream(FilePath);
Object[][] object = new Object[6][2];
Workbook wb = Workbook.getWorkbook(fs);
//locate the excel file in the local machine
Sheet sheet = wb.getSheet("IOResult");
int i=1; //avoid header row
while(!(sheet.getCell(0, i).getContents().equals("end"))) //read data till it reaches the cell whose text is ‘end’
{
object[i-1][0]=sheet.getCell(0, i).getContents();
object[i-1][1]=sheet.getCell(1, i).getContents();
System.out.print(sheet.getCell(0, i).getContents() + "\t");
System.out.print(sheet.getCell(1, i).getContents() + "\t");
System.out.println();
i++;
}
return Arrays.asList(object);
}
#Test
public void testSquareOff(){
Assert.assertEquals(resultExpected, MathUtils.square(input));
}
}
Is there somebody who can point me in the right direction?
Thanks in advance
The method sheet.getCell(column, row).getContents() is returning a String, but your constructor expects int.
You may modify the two lines in the data() method:
object[i-1][0] = Integer.valueOf(sheet.getCell(0, i).getContents());
object[i-1][1] = Integer.valueOf(sheet.getCell(1, i).getContents());

How do I use DataProvider with Apache POI

Please help!. Am newbie with Selenium frameworks, I have a method that accepts 5 parameters for booking a party. It uses TestNG DataProvider to read from excel file. The problem is(as shown below) It uses JXL imports which only supports XLS files (excel 2003 or older). I need help with a similar code that uses Apache POI instead so that it will support XLSX and new versions of excel (2007+). Can someone help me please?
package com.suite1;
import util.TestUtil;
import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class CreatePartyTest extends TestBase1 {
Workbook wb;
Sheet sh1;
int numrow;
#BeforeTest
public void beforeTest() throws IOException
{
initialize();
if (TestUtil.isSkip("CreatePartyTest"))
{
throw new SkipException("Skipping test, check run mode");
}
dr.get(CONFIG.getProperty("testSiteName"));
getobject("signin_link").click();
getobject("username_Signin_input").sendKeys("alexy.dsouza");
getobject("password_input").sendKeys("testing123");
getobject("submit_button").click();
}
#Test(dataProvider="Partydata")
public void createParty (String Partyname, String Date, String Firstname, String Lastname, String email, String mobile) throws InterruptedException
{
getobject("party_link").click();
getobject("start_party_link").click();
getobject("partyname_input").sendKeys(Partyname);
getobject("partydate_input").sendKeys(Date);
getobject("hostfirstname_input").sendKeys(Firstname);
getobject("hostlastname_input").sendKeys(Lastname);
getobject("hostemail_input").sendKeys(email);
getobject("hostmobile_input").sendKeys(mobile);
getobject("make_reservation").click();
}
//source
#DataProvider(name="Partydata")
public Object[][] TestDataFeed(){
try {
// load workbook: this is where i store my excel
wb=Workbook.getWorkbook(new File("C://Workspace//Max//excelfiles//Partydata.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 [][] Accountdata=new Object[numrow-1][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0,j=1;i<numrow-1;i++){
// Fetch first row Accountname
Accountdata[i][0]=sh1.getCell(0,j).getContents();
// Fetch first row BankName
Accountdata[i][1]=sh1.getCell(1,j).getContents();
// Fetch everything else before an empty column
Accountdata[i][2]=sh1.getCell(2,j).getContents();
Accountdata[i][3]=sh1.getCell(3,j).getContents();
Accountdata[i][4]=sh1.getCell(4,j++).getContents();
}// Return 2d array object so that test script can use the same
return Accountdata;
}
}
I cannot solve your exact query , but you can take reference from my code in which i have used .xlsx workbook only and it is working fine for me.
I am able to read data from excel sheet(.xlsx) .
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProvidersConcept {
#DataProvider(name="Excelsheet")
public Object[][] readData() throws Exception
{
File f = new File("C:/Users/Vikrant/Documents/MavenTesting.xlsx");
FileInputStream fis = new FileInputStream(f);
XSSFWorkbook workBook = (XSSFWorkbook) WorkbookFactory.create(fis);
XSSFSheet sheet=workBook.getSheet("Sheet1");
Object array[][]=new Object[2][2];
for(int i =0;i<2;i++)
{
for( int j=0;j<2;j++)
{
array[i][j]=sheet.getRow(i).getCell(j).toString();
}
}
return array;
}
#Test(dataProvider="Excelsheet")
public void testData(String Username , String password)
{
System.out.println(Username);
System.out.println("Username tested successfully");
System.out.println(password);
System.out.println("password tested successfully");
}
}
enter code here

Crystal report SDK JRC Passing parameter giving error Error code:-2147217394 Error code name:missingParameterValueError

When I am trying pass paramaters from crystal report SDK and export my report to PDF. It is stand alone application so I can't user crystalreportviewer options but it is keep giving me error
com.crystaldecisions.sdk.occa.report.lib.ReportSDKParameterFieldException: InternalFormatterException---- Error code:-2147217394 Error code name:missingParameterValueError My code is given below please help
import com.crystaldecisions.reports.sdk.DatabaseController;
import com.crystaldecisions.reports.sdk.ReportClientDocument;
import com.crystaldecisions.reports.sdk.ParameterFieldController;
import com.crystaldecisions.sdk.occa.report.data.IConnectionInfo;
import com.crystaldecisions.sdk.occa.report.exportoptions.ExportOptions;
import com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat;
import com.crystaldecisions.sdk.occa.report.lib.ReportSDKException;
public class Test {
public static void main(String args[]) throws ReportSDKException, SQLException, FileNotFoundException, IOException{
try{
ReportClientDocument reportClientDoc = new ReportClientDocument();
reportClientDoc.open("Report.rpt",0);
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","P_DP",new Integer(22));
//Here I was calling switch database code
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getReportSource().export(ReportExportFormat.PDF);
IOUtils.copy(byteArrayInputStream, new FileOutputStream("new.pdf"));
reportClientDoc.close();
}
}
it starts working by just moving setting parameter code to above line. we need to set parameter before opening the report.
import com.crystaldecisions.reports.sdk.DatabaseController;
import com.crystaldecisions.reports.sdk.ReportClientDocument;
import com.crystaldecisions.reports.sdk.ParameterFieldController;
import com.crystaldecisions.sdk.occa.report.data.IConnectionInfo;
import com.crystaldecisions.sdk.occa.report.exportoptions.ExportOptions;
import com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat;
import com.crystaldecisions.sdk.occa.report.lib.ReportSDKException;
public class Test {
public static void main(String args[]) throws ReportSDKException, SQLException, FileNotFoundException, IOException{
try{
ReportClientDocument reportClientDoc = new ReportClientDocument();
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","P_DP",new Integer(22));
reportClientDoc.open("Report.rpt",0);
//Here I was calling switch database code
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getReportSource().export(ReportExportFormat.PDF);
IOUtils.copy(byteArrayInputStream, new FileOutputStream("new.pdf"));
reportClientDoc.close();
}
}

Categories