【发布时间】: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