简体   繁体   English

Apache POI XSSFWorkbook 为文件抛出 NullPointerException

[英]Apache POI XSSFWorkbook throwing NullPointerException for file

I have checked every possible question on here with a similar problem, and none of the solutions have worked.我在这里检查了所有可能的问题,有一个类似的问题,但没有一个解决方案有效。 I feel like I am missing something really obvious, but I just can't see it.我觉得我错过了一些非常明显的东西,但我就是看不到它。

I am on Windows 10, using Eclipse 2019, and the newest Apache POI jar files (not maven) with xmlbeans version 3.1.0. I am on Windows 10, using Eclipse 2019, and the newest Apache POI jar files (not maven) with xmlbeans version 3.1.0. I want to read an xlsx file, but every time I run my code (Which is a basic example I've seen used and run successfully on multiple websites and videos), I receive a "NullPointerException" at the line where I create my workbook:我想读取一个 xlsx 文件,但是每次我运行我的代码(这是我在多个网站和视频上看到并成功运行的一个基本示例)时,我都会在创建工作簿的行收到“NullPointerException” :

import java.io.File;
//import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
//import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class excelImportTest {


    public static void main (String args[]) throws IOException, InvalidFormatException {

      // Linking file to Workbook
      // ****Where exception is called every time****
      XSSFWorkbook wb = new XSSFWorkbook(new File("C:\\Users\\Owner\\Downloads\\TestData.xlsx"));

      // Pulling sheet from Workbook
      XSSFSheet sheet = wb.getSheetAt(0);

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

      // Traversing over each row of XLSX file
      while (rowIterator.hasNext()) {
          Row row = rowIterator.next();

          // For each row, iterate through each columns
          Iterator<Cell> cellIterator = row.cellIterator();

          while (cellIterator.hasNext()) {
              Cell cell = cellIterator.next();
              switch(cell.getCellType()) {
              case STRING:
                  System.out.print(cell.getStringCellValue() + "\t");
                  break;
              case NUMERIC:
                  System.out.print(cell.getNumericCellValue() + "\t");
                  break;
              case BOOLEAN:
                  System.out.print(cell.getBooleanCellValue() + "\t");
                  break;
              default :
              }
          }
      }
      wb.close();

Here is the exception I receive:这是我收到的异常:

Exception in thread "main" java.lang.ExceptionInInitializerError
    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:325)
    at excelImportTest.main(excelImportTest.java:62)
Caused by: java.lang.RuntimeException: Could not instantiate SchemaTypeSystemImpl (java.lang.reflect.InvocationTargetException): is the version of xbean.jar correct?
    at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.loadTypeSystem(Unknown Source)
    at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.<clinit>(Unknown Source)
    ... 16 more
Caused by: java.lang.reflect.InvocationTargetException
    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)
    ... 18 more
Caused by: 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)
    ... 22 more

I have tried every combination of options I can think of and suggestions I have found online:我已经尝试了我能想到的所有选项组合以及我在网上找到的建议:

  • I created a separate FileInputStream(new File(...)), and ran an if statement to see if it was null.我创建了一个单独的 FileInputStream(new File(...)),并运行了一个 if 语句来查看它是否是 null。 This returned "not null", but I still got the exception when it got to the line above这返回了“not null”,但是当它到达上面的行时我仍然得到了异常
  • I tried running the line with a nested new FileInputStream(new File(...)) format, and received the same error我尝试使用嵌套的 new FileInputStream(new File(...)) 格式运行该行,并收到相同的错误
  • I have been using a try-catch block for the exception, but it does not seem to flag the exception before aborting the program我一直在使用 try-catch 块来处理异常,但在中止程序之前它似乎没有标记异常
  • I have tried using the Apache-POI-included OCPPackage.open(new File(...)) approach, and get the same error我尝试使用包含 Apache-POI 的 OCPPackage.open(new File(...)) 方法,并得到相同的错误

Is there any obvious approach I am missing, or does this stem from some other issue in my setup?我是否缺少任何明显的方法,或者这是否源于我的设置中的其他问题?

Edit编辑

Since it seems my problem may be in the.jar files I am referencing, here is what I have as part of the file's build path:由于看来我的问题可能出在我引用的 .jar 文件中,因此这是文件构建路径的一部分:

在此处输入图像描述

I think you have not added the jars properly.我认为您没有正确添加 jars。

First go to this url: https://archive.apache.org/dist/poi/release/bin/ and download poi-bin-4.1.2-20200217.zip from there. First go to this url: https://archive.apache.org/dist/poi/release/bin/ and download poi-bin-4.1.2-20200217.zip from there.

Now extract the zip and add this jars to your project marked with red.现在提取 zip 并将此 jars 添加到标有红色的项目中。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

I have tested your code and its working.我已经测试了您的代码及其工作。

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Testing {
    public static void main(String args[]) throws IOException, InvalidFormatException {

        // Linking file to Workbook
        // ****Where exception is called every time****
        XSSFWorkbook wb = new XSSFWorkbook(new File("C:\\Users\\Anish\\Downloads\\TestData.xlsx"));

        System.out.println("Workbook loaded");

        // Pulling sheet from Workbook
        XSSFSheet sheet = wb.getSheetAt(0);

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

        // Traversing over each row of XLSX file
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                case STRING:
                    System.out.print(cell.getStringCellValue() + "\t");
                    break;
                case NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t");
                    break;
                case BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t");
                    break;
                default:
                }
            }
        }
        wb.close();

    }
}

Output: Output:

在此处输入图像描述

Now, if you are using maven in the project.Then, you don't need to add jars on the classpath.现在,如果您在项目中使用 maven。那么,您不需要在类路径中添加 jars。

Simply, add this dependency in the pom.xml .只需在pom.xml中添加此依赖项。

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

So after much troubleshoooting, I abandoned using the Apache POI jar files, and switched to using maven and adding apache poi as a dependancy, and my code now runs successfully. So after much troubleshoooting, I abandoned using the Apache POI jar files, and switched to using maven and adding apache poi as a dependancy, and my code now runs successfully.

Thank you too everyone who helped and made suggestions, though I am still not sure of the origin of the communication problem between Eclipse and the POI jar files.也感谢所有提供帮助和建议的人,尽管我仍然不确定 Eclipse 和 POI jar 文件之间的通信问题的根源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM