sharafi sharafi - 2 months ago 38
Java Question

what give java.lang.NoClassDefFoundError?

I want to read excel file but give

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject
at ExcelReader.main(ExcelReader.java:32)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject
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


please help me.
At first open .xlsx file and then give the first sheet.
at the end print data of excel file on console.
Ps : I add poi-ooxml-3.9-20121203.jar to my project.

import java.io.File;
import java.io.FileInputStream;
import javax.swing.text.html.HTMLDocument.Iterator;
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;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.util.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @author mohammad hosein
*
*/
public class ExcelReader {

/**
* @param args
*/
public static void main(String[] args) {
try
{
FileInputStream file = new FileInputStream(new File("E:\\test.xlsx"));

//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);

//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);

//Get iterator to all the rows in current sheet
java.util.Iterator<Row> rowIterator = sheet.iterator();

while(rowIterator.hasNext())
{
Row row = rowIterator.next();
java.util.Iterator<Cell> cellIterator = row.cellIterator();

while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t");
}
System.out.println("");
}
}
catch(Exception e)
{
System.out.println("EROR!");
}

//Get iterator to all cells of current row

}


}

Answer

Your code is irrelevant. NoClassDefFoundError happens when a class which was available at compilation time is unavailable at runtime. If you provided a full stacktrace, together with the actual name of the class which has not been found, more precise advice could be given.

Typically this happens when you are running your code with a different version of a JAR from the one used to build the code. A rogue JAR may come in from an application container or similar, and be placed earlier on the classpath than your proper JAR.

Update

Given the stacktrace you have added, you are lacking a transitive dependency of Apache POI: XMLBeans. You may be missing this JAR at runtime. This all depends on how exactly you are running your project.