java - 读取excel文件时出现空指针异常

标签 java nullpointerexception apache-poi poi-hssf

我正在编写一个函数来从 Excel (.xls) 读取数据,然后将其添加到 HashMap。

以前可以用,但现在出现错误。

我知道为什么会出现错误:这是因为我要读取数据的工作表(Htest)为空。

我检查了我的 Excel,有一张正确名称为“Htest”的工作表。

我还检查了工作簿中的工作表数量。它返回工作簿具有的正确工作表数

我检查了另一张表:它有效。

它只会对我正在处理的工作表抛出错误...

我不知道为什么工作簿中的工作表可用,但代码返回 null? 我错过了什么吗? 有人有同样的问题吗?或者你能给我一个使用它的提示吗?

谢谢。

错误是:

Method arguments: org.testng.TestRunner@2f6d9d1c, "/enigma"
java.lang.NullPointerException

com.validant.enigma3.common.UIMap.readControls(UIMap.java:133)
 com.validant.enigma3.common.UIMap.<init>(UIMap.java:32)
 com.validant.enigma3.common.TestBase.beforeSuite(TestBase.java:24)
 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 java.lang.reflect.Method.invoke(Method.java:606)
 org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
 org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
 org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
 org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
 org.testng.SuiteRunner.privateRun(SuiteRunner.java:277)
 org.testng.SuiteRunner.run(SuiteRunner.java:240)
 org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
 org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
 org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
 org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
 org.testng.TestNG.run(TestNG.java:1057)
 org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:74)
 org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:92)
 org.apache.maven.surefire.Surefire.run(Surefire.java:180)
 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 java.lang.reflect.Method.invoke(Method.java:606)
 org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
 org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)

代码是

private HashMap<String, MappingObj> readControls(String filepath, String sheetname)
            throws IOException {

        HashMap<String, MappingObj> controllist = new HashMap<String, MappingObj>();

        //System.out.println("FILE PATH = " + filepath);
        //System.out.println("SHEET NAME = " + sheetname);
        FileInputStream file = new FileInputStream(filepath);
        System.out.println(file.toString());

        //Get the workbook instance for XLS file 
        HSSFWorkbook myWorkBook = new HSSFWorkbook(file);

        //System.out.println("NUMBER of SHEET= "+myWorkBook.getNumberOfSheets());       

        HSSFSheet mySheet= myWorkBook.getSheet(sheetname); 


        if (myWorkBook.getSheet(sheetname)==null) 
            System.out.println("null");


        Iterator<Row> rowIter = mySheet.rowIterator();          
        rowIter.next();

        String[] arow = new String[3];

        while (rowIter.hasNext()) {
            HSSFRow row = (HSSFRow) rowIter.next();
            Iterator<Cell> cells = row.cellIterator();

            int i = 0;

            // Check data from current cell, there is data on next cell or
            // not?
            while (cells.hasNext()) {

                HSSFCell cell = (HSSFCell) cells.next();
                arow[i] = cell.getStringCellValue().trim();
                i++;
            }

            MappingObj mapObj = new MappingObj();

            mapObj.setCodeName(arow[0]);
            mapObj.setSelector(arow[1]);
            mapObj.setPath(arow[2]);

            controllist.put(arow[0], mapObj);
            file.close();
        }

        return controllist;
    }

Excel 是: 我的Excel中有5张纸,其顺序为: 登录FileUpload SimpleTasks Htest引用

所有工作表都具有相同的数据架构(有 3 列:控件名称、选择器、路径) 只是每列的数据不同。

工作表错误为Htest,其数据为

控件名称选择器路径

测试1 cssSelector测试2

最佳答案

您在评论中说过,给出 NPE 的行是:

Iterator<Row> rowIter = mySheet.rowIterator();

您的问题是您没有检查您尝试获取的工作表是否确实存在。如果您尝试获取名称无效的工作表,您将返回 null。来自 Workbook JavaDocs :

Returns: Sheet with the name provided or null if it does not exist

因此,您的代码应该更像是:

HSSFSheet mySheet= myWorkBook.getSheet(sheetname); 
if (mySheet == null) {
   throw new IllegalArgumentException("No sheet exists with name " + sheetName);
}

或者,从代码中返回 null,并在调用代码中检查该值(而不是捕获异常)。

如果您不确定您的工作簿到底有哪些工作表(在奇怪的情况下可能不是您所想的那样),请尝试:

for (int sn=0; sn < myWorkBook.getNumberOfSheets(); sn++) {
    System.out.println("Sheet " + sn + " is called " + myWorkBook.getSheetName(sn));
}

关于java - 读取excel文件时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488867/

相关文章:

java - 超出范围异常

java - 为什么我的 Spring @Autowired 字段为空?

java - 从 jsp 生成 Docx(或 doc)

java - 内存不足 : GC limit exceeded while creating XSSFWorkBook from InputStream

java - 在这种情况下如何返回带有流的列表?

java - 如何检测图像是照片、剪贴画还是线条图?

java - 在 NullPointerException 和 IllegalArgumentException 之间进行选择以在对象构造时发出错误信号

java - 复制到带有字符串的类时出现空指针异常

java - 如何读取上传后的大尺寸Excel文件

java - 如何在 Java 中创建一个新列表