java.lang.NoClassDefFoundError: org/apache/poi/ss/

2020-04-20 12:19发布

问题:

I've made a small application that reads from an excel (xls file) and displays the contents to a JTable. Everything is working fine in eclipse, yet when I create the jar file and try to run it, I get the following issue:

java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Row

The weird thing I find is that the issue is with the Row, when Workbook and Sheet is called before the row and gives no trouble (at least from what I can see).

I've researched alot and it mainly seems to be with the jar files not being in the Class-Path, but opening the jar and the manifest file I can see all the jars are present.

Class-Path: poi-ooxml-4.0.1.jar poi-4.0.1.jar commons-codec-1.11.jar commons-collections4-4.2.jar commons-math3-3.6.1.jar commons-compress-1.18.jar curvesapi-1.05.jar poi-ooxml-schemas-4.0.1.jar xmlbeans-3.0.2.jar

This is what I have in my pom.xml file:

<build>
 <plugins>
  <plugin>
    <!-- Build an executable JAR -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
       <manifest>
          <addClasspath>true</addClasspath>
          <classpathPrefix>./</classpathPrefix>
           <mainClass>com.clientdb.classes.DynamicRegForm</mainClass>
         </manifest>
       </archive>
     </configuration>
    </plugin>
  </plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
   </dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>

I have also tried downloading the jar files and adding them to the project instead of adding the dependency to pom file, and still the same error. Any ideas?

回答1:

Probably you are getting this only when you are running your jar because the dependencies are not available/packaged inside of it.

Try generating a "fat jar" (also known as uber-jar), it will package all your dependencies inside the jar:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <finalName>YOUR_JAR_FINAL_NAME</finalName>
            </configuration>
        </plugin>
    </plugins>
</build>

Documentation related to the maven-shade-plugin can be found in here

UPDATE: Since you are using a runnable jar file, you can follow this section of the documentation related to Executable Jars