【问题标题】:Retrieving Excel cell contents returns NullPointerException检索 Excel 单元格内容返回 NullPointerException
【发布时间】:2017-02-21 12:50:33
【问题描述】:

我正在尝试读取 Excel 工作表的内容,但我的方法不断抛出异常。我已经尝试了一切都无济于事,但我确信这是我没有看到的一个非常小的细节。有人可以用一双新的眼睛看我的代码,并可能指出我做错了什么。谢谢!

 /**
 * This method sets the path to the excel file and the excel sheet as well as
 * initializing the stream
 */
 public static void setExcelFile(String path, String sheetName) {
    try {
        FileInputStream excelFile = new FileInputStream(path);
        workbook = new XSSFWorkbook(excelFile);
        worksheet = workbook.getSheet(sheetName);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
 }


 /**
 * This method reads the cell data from the excel file
 */
public static String getCellData(int rowNum, int colNum) {
    try {
        //This is what is causing my nullpointerexception according to eclipse
        row = worksheet.getRow(rowNum);
        //cell = worksheet.getRow(rowNum).getCell(colNum);
        cell = row.getCell(colNum);
        String cellData = cell.getStringCellValue();
        return cellData;
    }
    catch (Exception e) {
        e.printStackTrace();
        return "Lactoferrin";
    }

}


/**
 * This is how i call both methods
 */
public static void main(String[] args) {
    try {
        ExcelUtility.setExcelFile(PATHTOTESTDATA, FILENAME);
        String cellContents = ExcelUtility.getCellData(1,0);
        System.out.println(cellContents);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

【问题讨论】:

  • 哪一行抛出异常?
  • getCellData() 方法,第 4 行
  • worksheet 必须为 null - sheetName 有效吗?

标签: java excel apache-poi fileinputstream


【解决方案1】:

找到了。我已将 excel 文件与类文件一起保存在一个包中,而 eclipse 找不到它……我不知道为什么。所以我把它移到项目根目录下的一个文件夹中,它工作了。

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    相关资源
    最近更新 更多