Skip to main content

Help needed to resolve issue with Java code to read .xlsx files

2 replies [Last post]
SrikarVR
Offline
Joined: 2011-10-03

Hi - I have written the below code to read the .xlsx files.

imports used:

import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

try {
fis = new FileInputStream(filename);
Workbook workbook = new XSSFWorkbook(fis);

sheetCount = workbook.getNumberOfSheets();
for (int i = 0; i < sheetCount; i++) {
sheet = workbook.getSheetAt(i);

rowCount = sheet.getPhysicalNumberOfRows();
for (int j = 0; j < rowCount; j++) {
Row row = sheet.getRow(j);

colCount = row.getPhysicalNumberOfCells();
for (int k = 0; k < colCount; k++) {
Cell cell = row.getCell(k);

int cellType = cell.getCellType(); //Getting a null pointer exception when the cell is empty
if (cellType == Cell.CELL_TYPE_NUMERIC) {
value = cell.getNumericCellValue() + "";
} else {
value = cell.getStringCellValue();
}

if (value != null)
System.out.print(value + "\t");
}
System.out.println();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
I get the folloing error:

1 java.lang.NullPointerException
at com.bgg.support.ProcessXLSX_SS.ReadSheet(ProcessXLSX_SS.java:36)
at com.bgg.support.ProcessXLSX_SS.main(ProcessXLSX_SS.java:62)

But I only use value = cell.getStringCellValue(); then it fails with below error where a numerica value is encountered...

java.lang.IllegalStateException: Cannot get a text value from a numeric cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:843)
at org.apache.poi.xssf.usermodel.XSSFCell.getRichStringCellValue(XSSFCell.java:294)
at org.apache.poi.xssf.usermodel.XSSFCell.getStringCellValue(XSSFCell.java:246)
at com.bgg.support.ProcessXLSX_SS.ReadSheet(ProcessXLSX_SS.java:40)
at com.bgg.support.ProcessXLSX_SS.main(ProcessXLSX_SS.java:62)

Thanks - Srikar

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
teleporter
Offline
Joined: 2012-05-14

This is totally just new for me. :sad:

suryahotha
Offline
Joined: 2012-05-04

In the Excel Sheet change the Category of that cell to text using Format Cells option. Hope this helps.

Surya Hota