Arnab Mitra
Arnab Mitra

Reputation: 5

Facing error while creating .doc file using apache poi

While creating a .DOC file using apache POI libraries, I face the error

"Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException at CreateDocument.main(CreateDocument.java:12)"

I would appreciate any help.

enter image description here

Upvotes: 0

Views: 369

Answers (1)

geco17
geco17

Reputation: 5294

I ran the following on my machine with no problems (the document is created):

public static void main(String...args) {

    try {
        XWPFDocument document = new XWPFDocument();

        FileOutputStream fos = new FileOutputStream("/home/william/Documents/test.docx");
        document.write(fos);

        document.close();

        System.out.println("Document created successfully");
    } catch (Exception e) {
        System.out.println("Document not created");
        e.printStackTrace();
    }

}

I used gradle to manage my dependencies. Not all the dependencies you mentioned in your comment are necessary for this example. In particular you only need the following:

dependencies {
    compile group: 'org.apache.poi', name: 'poi', version: '3.17'
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
}

What build tool are you using? Maven? Gradle?

Some comments on your original code:

1- Your try block doesn't have a catch block following it for exceptions. Consider catching the exception and displaying a meaningful error to the user if document creation fails. In my example I just printed the stacktrace but if this is a web app or a gui you would probably want to show the user a message.

2- You don't close the document after writing, which causes a resource leak.

The exception you are getting is because the class XmlException cannot be found. This class is in the xmlbeans-2.6.0.jar (or similar, this is the latest version at the time of writing).

Try adding the dependency to your build script

compile group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '2.6.0'

Upvotes: 1

Related Questions