Error while reading excel file in selenium - java

package ReadExcelData;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadandWriteExcel {
public static void main(String []args){
try {
File src = new File("C:\\poi\\ExcelData\\TestExcelData.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh1= wb.getSheetAt(0);
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());
System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());
wb.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Hi,
I Downloaded poi-4.0.0 and added external jar file to my project. After setup of project I created excel file and wrote java program to read from excel file
While run time I am getting error
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/compress/archivers/zip/ZipFile
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:298)
at org.apache.poi.ooxml.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:307)
at ReadExcelData.ReadandWriteExcel.main(ReadandWriteExcel.java:19)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.compress.archivers.zip.ZipFile
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more`enter code here`

You need to add commons-compress-1.18.jar into your project build path.
https://commons.apache.org/proper/commons-compress/download_compress.cgi

Related

NoClassDefFoundError while reading Excel sheet data and printing values

NoClassDefFoundError while reading Excel sheet data and printing values
I am getting classnotfound exception for below code :
package practice;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class dataDriven {
public static void main(String[] args) throws FileNotFoundException,IOException
{
FileInputStream fis = new FileInputStream("C://Users//484834//testdata.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
wb =null;
int sheets = wb.getNumberOfSheets();
System.out.println("Number of sheets is "+sheets);
}
}
output is :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap
at practice.dataDriven.main(dataDriven.java:14)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.ListValuedMap
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
It looks like you are missing the the jar file. You can add commons-collections4-x.jar in build path.
URL for the same is -https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.2
Hope this will resolve your issue.

BIRT : How to generate and save a report in PDF format using RE API

I am working on a project to generate BIRT reports in PDF format. The application is not meant to be a web application. I tried to follow the Report Engine API example on this link http://wiki.eclipse.org/Simple_Execute_(BIRT)_2.1 but I get an error when I run (Run as -> Java Application) the code. My code is as below.
My code is as follows:
package birt.classicmodels.offices;
import java.util.logging.Level;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.PDFRenderOption;
public class ExecuteReport {
public static void main(String[] args) {
ExecuteReport er = new ExecuteReport();
try {
er.executeReport();
} catch(Exception ex) {
System.out.println(ex.toString());
}
}
public void executeReport() throws EngineException {
IReportEngine engine = null;
EngineConfig config = null;
IReportEngineFactory factory = null;
Object factoryObj = null;
try {
config = new EngineConfig();
config.setBIRTHome("C:\\birt-runtime-4.6.0-20160607\\ReportEngine");
config.setLogConfig("C:\\temp\\test", Level.FINEST);
Platform.startup(config);
factoryObj = Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
factory = (IReportEngineFactory) factoryObj;
engine = factory.createReportEngine(config);
// Open the report design
IReportRunnable design = null;
String designPath = "C:\\birt-runtime-4.6.0-20160607\\ReportEngine\\samples\\hello_world.rptdesign";
design = engine.openReportDesign(designPath);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
PDFRenderOption PDF_OPTIONS = new PDFRenderOption();
PDF_OPTIONS.setOutputFileName("C:\\temp\\test.pdf");
PDF_OPTIONS.setOutputFormat("pdf");
task.setRenderOption(PDF_OPTIONS);
task.run();
task.close();
engine.destroy();
} catch(final Exception ex) {
ex.printStackTrace();
} finally {
Platform.shutdown();
}
}
}
SETUP:
I installed the BIRT designer using the complete BIRT designer download.
I added all the .jars under the libs folder of the BIRT runtime folder to my build path.
The main method was not part of the example I added it with the intention of getting the report saved to my file system.
The design template I'm referencing is the design example that comes with the BIRT engine.
ISSUES:
When I run the code (Run as -> Java Application) I get the following errors:
A pop up dialog with the message:
Java Virtual Machine Launcher
Error: A JNI error has occured, please check your installation and try again
After I click OK on the message dialog, the console is populated with the following error:
Exception in thread "main" java.lang.NoClassDefFoundError:
org/eclipse/birt/core/framework/PlatformConfig
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetMethodRecursive(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException:
org.eclipse.birt.core.framework.PlatformConfig
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
I think you are missing following dependency
<dependency>
<groupId>org.eclipse.birt.runtime</groupId>
<artifactId>org.eclipse.birt.runtime</artifactId>
<version>4.6.0-20160607</version>
</dependency>

i get ClassNotFoundException when i try to read from excel file

When i try to read from excel file using apace poi i get the ClassNotFoundException followed by other errors and i have imported all the necessary jar files in the reference library
by the way i'm still new to coding
heres the code :
import java.io.*;
import java.io.File;
import java.io.FilterInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.*;
import org.apache.poi.*;
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.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream F = new FileInputStream("Carbcounting.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(F);
XSSFSheet sheet = wb.getSheetAt(0);
FormulaEvaluator formulaEva = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet){
for(Cell cell : row){
System.out.print(cell.getStringCellValue());
}
}
System.out.println();
}
}
and heres all the errors i'm getting when i try to run it :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap
at project.Test.main(Test.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.ListValuedMap
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
You need to Add commons-collections4-x.x.jar file in your build path and try it again. It should work.
Get it from here: https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0
Also, just adding up:
You are getting this error(NoClassDefFoundError) majorly for two reasons:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.

Java - Trouble loading file NoClassDefFoundError

Solved: I needed to add another jar file that was in another folder
All of my code is below. It is from this website. I've read over multiple examples of loading XSSF files, but I continue to get this same error. All of my imports are correct, but my only guess would be my file path. But it seems correct and gives me no errors
package testcode;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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.xssf.usermodel.XSSFWorkbook;
public class TestCode {
public static void main( String[] args ) throws IOException {
InputStream ExcelFileToRead = new FileInputStream("C:/Users/[name]/Desktop/Book1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while ( rows.hasNext() ) {
row = ( XSSFRow ) rows.next();
Iterator cells = row.cellIterator();
while( cells.hasNext() ) {
cell = ( XSSFCell ) cells.next();
if ( cell.getCellType() == XSSFCell.CELL_TYPE_STRING ) {
System.out.print( cell.getStringCellValue() + " " );
}
else if( cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC ) {
System.out.print( cell.getNumericCellValue() + " " );
}
else {
}
}
System.out.println();
}
}
Error message:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
at testcode.TestCode.main(TestCode.java:20)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
NoClassDefFoundError . This exception is encountered, when there is a class file or api your code depends on,is present at compile time but not found at runtime.
Please check the jars available at runtime or compare the runtime and compile dependencies.

exception while using excel workbook

I am getting these exceptions in my code while i m writing some data in excel workbook using poi jars:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at WorkBookDemo.main(WorkBookDemo.java:27)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.UnsupportedFileFormatException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 13 more
I added following jars:
xmlbeans-2.4.0
poi-ooxml-schemas-3.11
poi-3.11
commons-logging-1.1
dom4j-1.6.1
log4j-1.2.17
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WorkBookDemo {
public static void main(String[] args)
{
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Employee Data");
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
data.put("2", new Object[] {1, "Amit", "Shukla"});
data.put("3", new Object[] {2, "Lokesh", "Gupta"});
data.put("4", new Object[] {3, "John", "Adwards"});
data.put("5", new Object[] {4, "Brian", "Schultz"});
//Iterate over data and write to sheet
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);
else if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
}
}
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("exps.xlsx"));
workbook.write(out);
out.close();
System.out.println("exps.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
FileOutputStream out = new FileOutputStream(new File("exps.xlsx"));
A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.
Since you are explicitly creating a File object, and passing the same to FileOutputStream constructor. It assumes that the file "exps.xlsx" is already created. [Reference.]
Incase, it is not, you simply pass the name of the file in FileOutputStream constructor.
FileOutputStream out = new FileOutputStream("exps.xlsx");
This will automatically create the file, incase it is already not created.
Moreover, I tested your given code and used the following Maven dependency and it worked.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10</version>
</dependency>
Incase you are not using a maven project, you can explicitly add the aforementioned jars of the aforementioned versions.
You have missing jar-files. I ran your code in my workspace and I added required jars to build path. It worked successively.
org/apache/poi/UnsupportedFileFormatException is under poi-x.xx-xxx-xx.jar
No error in your code it is correct. Add jars to build path.
the below list of jars required for apachePOI library should all be of same version like shown below :
org.apache.poi.3.11
org.apache.poi-ooxml.3.11
org.apache.poi-ooxml-schemas.3.11
if the above jars of the same library are of different versions, then u will get the exception as "java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException"
you can check for duplicate poi jars as well, suppose you need poi-ooxml-3.9. jar. but in your lib folder there is both poi-ooxml-3.11.jar, poi-ooxml-3.9.jar then remove poi-ooxml-3.11.jar, it should work then.

Categories