使用 Apache POI 库从 Excel (xlsx) 文件读取会抛出 NullPointerException

Reading from an Excel (xlsx) file using Apache POI library throws NullPointerException

我正在使用 Eclipse IDE 构建一个 JSP 网络应用程序。 Web 应用程序在 tomcat 服务器版本 7 上加载没有问题。我们有一个新的要求来读取 xls 和 xlsx 文件。所以我们使用 Apache POI 库 (4.1.2) 来实现如下:我已经删除了其他代码,因为它们与此无关 post

FileInputStream file = new FileInputStream(new File(args[0]));

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file); //<- This is where the exception occurs

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

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();

但是在执行时我们得到以下异常。我试过谷歌搜索但没有找到相关帮助。你能帮忙吗?

SEVERE: Servlet.service() for servlet [UploadEstimates] in context with path [/AD] threw exception [Servlet execution threw an exception] with root cause
java.lang.NullPointerException
at org.apache.xmlbeans.impl.schema.ClassLoaderResourceLoader.getResourceAsStream(ClassLoaderResourceLoader.java:33)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.getLoaderStream(SchemaTypeSystemImpl.java:2249)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.<init>(SchemaTypeSystemImpl.java:1522)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.initFromHeader(SchemaTypeSystemImpl.java:273)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.<init>(SchemaTypeSystemImpl.java:185)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.loadTypeSystem(Unknown Source)
at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.<clinit>(Unknown Source)
at sun.misc.Unsafe.ensureClassInitialized(Native Method)
at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(Unknown Source)
at sun.reflect.ReflectionFactory.newFieldAccessor(Unknown Source)
at java.lang.reflect.Field.acquireFieldAccessor(Unknown Source)
at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:775)
at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument.<clinit>(Unknown Source)
at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument$Factory.parse(Unknown Source)
at org.apache.poi.xssf.model.ThemesTable.<init>(ThemesTable.java:86)
at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:61)
at org.apache.poi.ooxml.POIXMLDocumentPart.read(POIXMLDocumentPart.java:684)
at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:180)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:288)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:342)
at com.MyClient.AD.util.UploadEstimateUT.start(UploadEstimateUT.java:85)
at com.MyClient.AD.util.UploadEstimates.doPost(UploadEstimates.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1195)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

这是我引用 POI 文件的方式: MyProject -> 右键单击​​ -> Build Path -> Configure Built Path -> Libraries 选项卡并添加以下 jars

这就是我执行应用程序的方式 运行 -> 运行 配置... -> 类路径选项卡 -> 确保此处引用了所有 jar 文件,包括 Apache POI -> 应用 and/or 运行.


更新 1(2020 年 2 月 28 日)

我尝试了与 java 应用程序相同的代码(使用 POI 库从 excel 读取)并且它按预期工作。

我在调试 JSP Web 应用程序时注意到的另一件事是,控制权直接转移到 finally 块,而不是一般的 Exception 块。不知道为什么。


更新 2(2020 年 3 月 3 日)

我在我的同事系统中配置了该项目,他也有 Eclipse IDE,但使用 Tomcat 服务器版本 9.0.31,它在他的机器上运行。

然后我安装了 Tomcat 服务器版本 9.0.31 并从一个单独的工作区配置了项目,但是在执行时我遇到了同样的异常。我无法理解有什么区别。

我们都在为企业 Java 开发人员使用 Eclipse IDE。版本:2019-09 R (4.13.0) 内部版本号:20190917-1200


更新 3(2020 年 3 月 6 日)

magicmn,更新到工厂方法后出现以下异常

    SEVERE: Servlet.service() for servlet [UploadEstimates] in context with path [/AD] threw exception [Servlet execution threw an exception] with root cause
java.lang.NullPointerException
    at org.apache.xmlbeans.impl.schema.ClassLoaderResourceLoader.getResourceAsStream(ClassLoaderResourceLoader.java:33)
    at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.getLoaderStream(SchemaTypeSystemImpl.java:2249)
    at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.<init>(SchemaTypeSystemImpl.java:1522)
    at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.initFromHeader(SchemaTypeSystemImpl.java:273)
    at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.<init>(SchemaTypeSystemImpl.java:185)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.loadTypeSystem(Unknown Source)
    at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.<clinit>(Unknown Source)
    at sun.misc.Unsafe.ensureClassInitialized(Native Method)
    at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(Unknown Source)
    at sun.reflect.ReflectionFactory.newFieldAccessor(Unknown Source)
    at java.lang.reflect.Field.acquireFieldAccessor(Unknown Source)
    at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
    at java.lang.reflect.Field.get(Unknown Source)
    at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:775)
    at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument.<clinit>(Unknown Source)
    at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument$Factory.parse(Unknown Source)
    at org.apache.poi.xssf.model.ThemesTable.<init>(ThemesTable.java:86)
    at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:61)
    at org.apache.poi.ooxml.POIXMLDocumentPart.read(POIXMLDocumentPart.java:684)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:180)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:288)
    at org.apache.poi.xssf.usermodel.XSSFWorkbookFactory.createWorkbook(XSSFWorkbookFactory.java:97)
    at org.apache.poi.xssf.usermodel.XSSFWorkbookFactory.createWorkbook(XSSFWorkbookFactory.java:125)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:327)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:295)
    at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:276)
    at com.MyClient.AD.util.UploadEstimateUT.start(UploadEstimateUT.java:90)
    at com.MyClient.AD.util.UploadEstimates.doPost(UploadEstimates.java:108)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

我尝试 post 发表评论,但我的等级不允许我这样做。这不是一个答案(所以请不要苛刻),但这是我在你的情况下所做的(上个月我一直在处理 java 和 excel 文件,我我很好)。

File myFile=new File(args[0]);
if(myFile==null)System.out.println("my file is null");else System.out.println("my file is NOT null");
FileInputStream file = new FileInputStream(new File(args[0]));


你可以post你的结果,我会试一试。

您确定在尝试读取文件之前已完成上传吗? 因为从堆栈跟踪: 在 com.MyClient.AD.util.UploadEstimateUT.start(UploadEstimateUT.java:85) 开始上传

我知道当我从 Spring 休息服务收到资源时,在保存并重新打开它之前,我遇到了类似的 POI 问题。

您是否尝试过以下操作?

  • 把文件写到别处。那就读吧。

  • 使用 xls 工作簿。通常我建议使用 Workbook workbook = WorkbookFactory.create(input); 来创建您的工作簿。 POI 的一大优势是它提供了 Workbook 接口以对 XLS 和 XLSX 文件进行标准化操作。

ClassLoaderResourceLoader 的第 33 行抛出 NullPointerException。该行是:

return _classLoader.getResourceAsStream(resourceName);

这意味着 _classLoader 为空。 _class加载程序传递给构造函数。

ClassLoaderResourceLoader 对象创建于 SchemaTypeSystemImpl 的第 182 行:

_classloader = indexclass.getClassLoader();
...
_resourceLoader = new ClassLoaderResourceLoader(_classloader);

表示_classloader为空,表示indexclass.getClassLoader()为空。

什么时候 getClassLoader() return 可以为空? documentation 表示:

Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

Bootstrap?它会响铃吗?是的,您将所有 jar 放在 Bootstrap 条目中,这意味着它们由 bootstrap class 加载程序加载。正如我在评论中所说(您似乎忽略了这一点),jar 的正确位置是应用程序的 WEB-INF\lib 目录。所以只要把它们放在那里就可以了。