Rachana Rachana - 4 months ago 74
Java Question

Null pointer exception while reading an excel file in java

I am new to Java and I am trying to read an excel file.
jars included:

log4j-1.2.17
,
poi-3.9
,
poi-ooxml-3.5-beta5
,
poi-ooxml-3.7-20101029
,
poi-ooxml-schemas-3.7-beta1
,
xmlbeans-2.5.0
,
xmlbeans-xmlpublic-2.4.0


package net.codejava.excel;

import java.io.*;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class SPACE_CreateThroughExcel{
public static void main(String[] args) throws Exception{

SPACE_CreateThroughExcel create = new SPACE_CreateThroughExcel();
create.read();
}
public void read(){

try {
String excelFilePath = "C:/Users/Rachana/workspace/SPACEOM/WebContent/Data/Data.xlsx";
InputStream is = new FileInputStream(new File(excelFilePath));
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(is);
XSSFSheet ws = wb.getSheetAt(0);

int rowNum = ws.getLastRowNum() + 1;
System.out.println(rowNum);
int colNum = ws.getRow(0).getLastCellNum();

String[][] data = new String[rowNum][colNum];
for(int i=0; i< rowNum; i++){
XSSFRow row = ws.getRow(i);
for(int j=0;j<colNum;j++){
XSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[i][j] = value;
System.out.println(value);
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static String cellToString(XSSFCell cell){
int type;
Object result;
type = cell.getCellType();

switch(type){
case 0:
result = cell.getNumericCellValue();
break;
case 1:
result = cell.getStringCellValue();
break;
default:
throw new RuntimeException("No support");

}
return result.toString();
}
}


This is my code. I am trying to read the cells of excel file into a 2D array which I want to later use in my jsp file. When I run it it shows the following errors:

at net.codejava.excel.SPACE_CreateThroughExcel.cellToString(SPACE_CreateThroughExcel.java:46)
at net.codejava.excel.SPACE_CreateThroughExcel.read(SPACE_CreateThroughExcel.java:30)
at net.codejava.excel.SPACE_CreateThroughExcel.main(SPACE_CreateThroughExcel.java:64)


My excel file is something like this:

SPLD_DeviceID_Mfg SPLD_DeviceID_ModelNo SPLD_DeviceID_SrNo
4
apl 3


Some of the fields in my excel file are empty. I need to store the empty value in my array for later use. I am checking only the types for integer and String. What to do in case of null?

Answer

It seems the sheet you are fetching doesn't exist. So probably the error is in this line : XSSFSheet ws = wb.getSheet("SPACE_License");. Do verify it. ws is coming out as null.

Comments