Flow Flow - 2 months ago 8
Java Question

Program halts trying to read Excel workbook (Apache POI)

I am trying to read an Excel workbook (

) but the program just halts when initializing a
. I'm not sure what's happening as it doesn't give any errors.

When I say halt, I mean the program just pauses. It's still running but I feel like it's stuck, not sure.

import java.io.File;
import java.io.FileInputStream;

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;

public class ExcelReader
private String excelFilePath;
private FileInputStream inputStream;
private Workbook workbook;
private Sheet sheet;

// Constructors
public ExcelReader() {
try {
// Get path to excel workbook and put in stream
excelFilePath = "/home/flow/project/mydata.xlsx";
inputStream = new FileInputStream(new File(excelFilePath));

// Get type of workbook (Excel 2003 or Excel 2007+)
workbook = getWorkbook();

} catch (Exception e) {

// Get type of workbook (Excel 2003 or Excel 2007+)
private Workbook getWorkbook() {
Workbook work = null;

try {
if(excelFilePath.endsWith("xlsx")) {
System.out.println("In firstIf"); // Prints this
work = new XSSFWorkbook(inputStream); // Gets stuck here
System.out.println("After XSSF"); // Never prints this
else if(excelFilePath.endsWith("xls")) {
work = new HSSFWorkbook(inputStream);
throw new IllegalArgumentException("The specified file is not an Excel file");

} catch (Exception e) {

return work;

What am I doing wrong? Why doesn't the program ever move on to the next line?


I couldn't figure out why the program kept stopping so I downgraded to version 3.9 and got the code to work. Thanks to Gagravarr, I was able to cut down on the usage of memory by getting rid of the whole getWorkbook() method and the FileInputStream class.

Change workbook = getWorkbook() to this:

workbook = WorkbookFactory.create(new File(excelFilePath));

It will create the appropriate XSSFWorkbook or HSSFWorkbook.

Source: WorkbookFactory.create(...)