使用apache poi创建.doc文件时遇到错误

时间:2018-03-11 07:08:18

标签: apache-poi

使用apache POI库创建.DOC文件时,我面临错误

  

“线程中的异常”主“java.lang.NoClassDefFoundError:   org / apache / xmlbeans / XmlException at   CreateDocument.main(CreateDocument.java:12)“

我将不胜感激。

enter image description here

1 个答案:

答案 0 :(得分:1)

我在我的机器上运行了以下操作,没有任何问题(文档已创建):

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();
    }

}

我使用gradle来管理我的依赖项。并非您在评论中提到的所有依赖项都是此示例所必需的。特别是您只需要以下内容:

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

您使用的构建工具是什么? Maven的?摇篮?

对原始代码的一些评论:

1-您的try块没有跟踪异常的catch块。如果文档创建失败,请考虑捕获异常并向用户显示有意义的错误。在我的示例中,我刚刚打印了堆栈跟踪,但如果这是一个Web应用程序或gui,您可能希望向用户显示一条消息。

2-写入后不要关闭document,这会导致资源泄漏。

您获得的异常是因为无法找到类XmlException。这个类在xmlbeans-2.6.0.jar(或者类似,这是撰写本文时的最新版本)。

尝试将依赖项添加到构建脚本

compile group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '2.6.0'
相关问题