【问题标题】:Nullpointer Exception While Using Trying to Read Excel in Selenium在 Selenium 中尝试读取 Excel 时出现 Nullpointer 异常
【发布时间】:2018-10-26 18:20:48
【问题描述】:

大家好,我搜索了所有解决方案但找不到。为什么我不知道为什么会出现空指针异常。请帮我解决这个问题。它仅显示为路径错误,但我仅正确指定了它。

我的代码:

package UsingExcel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.sun.rowset.internal.Row;

public class Demo 
{

    public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
    {
        File file = new File(filepath); // line 21

        FileInputStream stream = new FileInputStream(file);

        Workbook Mybook = null;

        String FileExtensionnname = filename.substring(filename.indexOf("."));

        if(FileExtensionnname.equals(".xlsx"))
        {
            Mybook = new XSSFWorkbook(stream);
        }
        else if(FileExtensionnname.equals(".xls"))
        {
            Mybook = new HSSFWorkbook(stream);
        }

        Sheet filesheet = Mybook.getSheet(Sheetname);

        int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();

        for(int i=0;i<rowcount+1;i++)
        {
            org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);

            for(int j=0;j<row.getLastCellNum();j++)
            {
                System.out.println(row.getCell(j).getStringCellValue()+ "||");
            }

            System.out.println();
        }
    }

    public static void main(String[] args) throws IOException
    {
        Demo excelfile =  new Demo();

        String filepath = System.getProperty("E:\\Mybook.xlsx");

        excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
        }

}

我的错误是:

Exception in thread "main" java.lang.NullPointerException
    at java.io.File.<init>(Unknown Source)
    at UsingExcel.Demo.ReadExcel(Demo.java:21)
    at UsingExcel.Demo.main(Demo.java:61)

希望您了解我的问题,请解决此问题。但是当我使用 Excel 测试登录页面时不会出现问题,现在我尝试在 控制台不工作。

【问题讨论】:

标签: java selenium selenium-webdriver apache-poi testng


【解决方案1】:

你的文件路径应该是

String filepath = "E:\\Mybook.xlsx",不要使用System.getProperty

来自文档:

获取指定键所指示的系统属性

一个空值被传递给你的方法ReadExcel(...),因为没有System属性被定义为E:\Mybook.xlsx

【讨论】:

  • 愚蠢的错误你是对的,我改为字符串 filepath = "E:\\Mybook.xlsx";现在它开始工作了。谢谢@Nicholas K
猜你喜欢
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
  • 2016-05-19
相关资源
最近更新 更多