Error: Could not find or load main class excel2JSON.excel - java

package excel2JSON;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
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.json.JSONArray;
import org.json.JSONObject;
public class excel {
public static void main(String[] args)
{
String str = ExcelToJSON(new File ("C:\\workbook.xlsx"));
System.out.println("JSON = " + str);
}
private static String ExcelToJSON(File file_open)
{
JSONObject json = null;
try {
FileInputStream input = new FileInputStream(file_open);
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = workbook.getSheetAt(0);
json = new JSONObject();
JSONArray rows = new JSONArray();
for (Iterator<Row> rows_it = sheet.rowIterator(); rows_it.hasNext();) {
Row row = rows_it.next();
JSONObject jason_row = new JSONObject();
JSONArray cells = new JSONArray();
for (Iterator<Cell> cells_it = row.cellIterator(); cells_it.hasNext();) {
Cell cell = cells_it.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
double numeric=cell.getNumericCellValue();
cells.put(String.valueOf(numeric));
break;
case Cell.CELL_TYPE_STRING:
cells.put(cell.getStringCellValue());
break;
}
}
jason_row.put("cell", cells);
rows.put(jason_row);
}
// Create the JSON.
json.put("rows", rows);
} catch (Exception e) {
e.printStackTrace();
}
// Get the JSON text.
return json.toString();
}
}
getting this error:
Error: Could not find or load main class excel2JSON.excel
I don't know why i am getting this error. I am new to Java and i need help to fix this issue. I am trying to convert Excel file to JSON document. This is the code i wrote for that but i am getting issue when i run the program in Eclipse.

The most common cause of this error in eclipse is when you have moved the class around, Eclipse will be trying to use an outdated run configuration which will not work.
Click the down arrow next to the green play button in Eclipse, select Run Configurations.
Delete the references to this class, then close that window, select the excel class. Click the down arrow next to the play button again and select run as Java Application.

Related

How to call an method which resides in different project?

I have Two separate projects in eclipse work space is same but different two projects.
Suppose two project A & B, i have call an class suppose Test.java having main method and one simple display method from project b and i need to call from project B.In main method i am calling display method of Test.java class.
And suppose i have another class Execute.java in project A so i need call class from Project B in to Project A in Execute.java class, how do i do that?
Any suggestion will be appreciated
File : TestNGCreator.java
package testDrivers;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import projlib.Globals;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;
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.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestNGCreator
{
public void runTestNGTest() throws IOException
{
//Create an instance on TestNG
TestNG myTestNG = new TestNG();
//Create an instance of XML Suite and assign a name for it.
XmlSuite mySuite = new XmlSuite();
mySuite.setName(Globals.SUITE_NAME);
//Create a list of XmlTests and add the Xmltest you created earlier to it.
List<XmlTest> myTests = new ArrayList<XmlTest>();
XSSFSheet excelWSheet = null;
XSSFWorkbook excelWBook = null;
XSSFCell cell = null;
XSSFRow row = null;
Double dblCellVal;
String strCellVal = null;
Boolean blnCellVal;
FileInputStream excelFile = new FileInputStream(Globals.CONFIG_FILE_DIR);
excelWBook = new XSSFWorkbook(excelFile);
//excelWSheet = excelWBook.getSheet(Globals.CONFIG_SHEET_NAME);
Iterator <Row> rowIterator = excelWSheet.iterator();
//Iterator <Cell> cellIterator = row.cellIterator();
String testName = null;
int colCount;
if (rowIterator.hasNext())
{
row = (XSSFRow) rowIterator.next();
colCount = row.getPhysicalNumberOfCells();
}
while (rowIterator.hasNext())
{
row = (XSSFRow) rowIterator.next();
Iterator <Cell> cellIterator = row.cellIterator();
int curCell = 0;
while (cellIterator.hasNext())
{
cell = (XSSFCell) cellIterator.next();
curCell++;
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
dblCellVal = cell.getNumericCellValue();
strCellVal = dblCellVal.toString();
break;
case Cell.CELL_TYPE_STRING:
strCellVal = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
blnCellVal = cell.getBooleanCellValue();
strCellVal = blnCellVal.toString();
break;
}
//If it is first cell then store the Test Name
if (cell.getColumnIndex()== 0)
{
testName = strCellVal;
}
if (curCell == 5) {
if (strCellVal.equals("1.0")) {
//Adding to suite
//Create an instance of XmlTest and assign a name for it.
XmlTest myTest = new XmlTest(mySuite);
myTest.setName(testName);
//Add any parameters that you want to set to the Test.
Map<String, String> testngParams = new HashMap<String,String> ();
testngParams.put("testId", testName);
myTest.setParameters(testngParams);
//Create a list which can contain the classes that you want to run.
List<XmlClass> myClasses = new ArrayList<XmlClass> ();
myClasses.add(new XmlClass("TestDriver"));
//Assign that to the XmlTest Object created earlier.
myTest.setXmlClasses(myClasses);
//Adding the test to test list created earlier
myTests.add(myTest);
break;
}
}
}
}
excelWBook.close();
//add the list of tests to your Suite.
mySuite.setTests(myTests);
//Add the suite to the list of suites.
List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
mySuites.add(mySuite);
//Set the list of Suites to the testNG object you created earlier.
myTestNG.setXmlSuites(mySuites);
File file = new File(Globals.TESTNG_FILE_NAME);
System.out.println("File is: " + file);
FileWriter writer = new FileWriter(file);
writer.write(mySuite.toXml());
writer.close();
//invoke run() - this will run your class.
//myTestNG.run();
}
public static void main(String args[]) throws IOException
{
TestNGCreator testDriver = new TestNGCreator();
testDriver.runTestNGTest();
}
}
So i need to call main method.
You can do it by following below steps.
Build the first project and create jar
Right click on second project ->Build Path->Configure Build Path->Libraries->Add External Jars
Use the class from first project
Or
If you want to send/receive data from any web service, Please expose your method as REST API such a way that your web service will accept it.
You can use Apache HttpComponents to expose your method to web service, Please find the below sample code.
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config)
.disableContentCompression().setSSLSocketFactory(sslsf).build();
HttpPost postRequest = new HttpPost(url);
client.execute(postRequest);
If you are not using Maven or Gradle you can perform the following steps in order to include the project:
Properties -> Build Path -> Projects -> Add , add the project you want.

Nullpointer Exception While Using Trying to Read Excel in Selenium

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

Apache poi XLSX to XLS

I'm working with apache poi, i read some xlsx file, process it and then export them in xlsx format as well. But now i have the requirement of the export format to be XLS (this is to support old devices). Is there an easy way of convert the code-generated xlsx file to xls?
The all process is made with XSSF implementation.
Thanks in advance.
I agree with centic answer, but I want to add a few lines of code.
You said that you are using XSSF implementation.
So, for the workbook that you are saving do the following changes:
change XSSFWorkbook x = new XSSFWorkbook();
to Workbook x = new HSSFWorkbook();
where Workbook is import from org.apache.poi.ss.usermodel.Workbook;
Similarly
Change XSSFRow instantiation from
XSSFRow r = newXSSF();
to Row r = new HSSFRow();
and import the Row from org.apache.poi.ss.usermodel.Row;
Like the same way, change Cell instantiation to ss.usermodel package.
And finally save your HSSF workbook with .xls extension.
You will need to switch to the "ss" implementation which allows to transparently work with both HSSF (=XLS) and XSSF (=XSLX), see http://poi.apache.org/spreadsheet/converting.html for some details of the original HSSF -> SS switch which should also shed some light on supporting it for the other way around.
Then only the two constructors for HSSFWorkbook/XSSFWorkbook are needed to decide which of the two formats you want to produce.
I have faced same scenario and implemented below code for Coverting XLSX to XLS using Java
Below code will read it from directory and process using apache camel (polling file from path) and apace poi
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Optional;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class ExcelFileProcessor implements Processor {
final Logger logger = LoggerFactory.getLogger(getClass());
#Value("${test.dir.in}")
private String inDir;
#Override
public void process(Exchange exchange) throws Exception {
logger.info("Entry-ExcelFileProcessor- Process method");
long start = System.currentTimeMillis();
String fileNameWithExtn=(String) exchange.getIn().getHeader("camelFileName");
Long originalFileSize = (Long) exchange.getIn().getHeader("CamelFileLength");
String fileNameWithOutExtn = fileNameWithOutExtn(fileNameWithExtn);
logger.info("fileNameWithExtn:{}" ,fileNameWithExtn);
logger.info("fileNameWithOutExtn:{}" ,fileNameWithOutExtn);
logger.info("originalFileSize:{}" ,originalFileSize);
try(InputStream in = exchange.getIn().getBody(InputStream.class);
XSSFWorkbook wbIn = new XSSFWorkbook(in);
Workbook wbOut = new HSSFWorkbook();) {
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(0);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK: break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
cellOut.setCellComment(cellIn.getCellComment());
}
}
}
File outF = new File(inDir+fileNameWithOutExtn+".xls");
try(OutputStream out = new BufferedOutputStream(new FileOutputStream(outF));){
wbOut.write(out);
}
}catch (Exception e) {
logger.info("Error during Excel file process:{}",e.getMessage());
}
long end = System.currentTimeMillis();
logger.info("Total time processed for file in - {} ms", (end - start));
logger.info("Exit-FileProcessor- Process method");
}
public String fileNameWithOutExtn(String fileName) {
return Optional.of(fileName.lastIndexOf('.')).filter(i-> i >= 0)
.map(i-> fileName.substring(0, i)).orElse(fileName);
}
}
If you are not using camel and want to get inputstream from file use below snippet
String inpFn = "input.xlsx";
String outFn = "output.xls";
InputStream in = new BufferedInputStream(new FileInputStream(inpFn));
try {
Workbook wbIn = new XSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new HSSFWorkbook();
//continue with above code

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

Categories