user2783755
user2783755

Reputation: 588

Open xls and xlsx with Apache POI

I want to open my excel file with Apache POI.

I don’t know if a file is xls or xlsx. I have only something like this:

InputStream myExcelFile = new ByteArrayInputStream(file.getData());

This way I can open xls file:

HSSFWorkbook hsf = new HSSFWorkbook(myxls);

And this way I can open xlsx file:

XSSFWorkbook xsf = new XSSFWorkbook(myxls);

How can I open both types of files if I don’t know format?

Upvotes: 2

Views: 6452

Answers (4)

Ankur Piyush
Ankur Piyush

Reputation: 308

Workbook wb = WorkbookFactory.create(myExcelFile);
if (wb instanceof HSSFWorkbook) {
    // do whatever
} else if (wb instanceof SXSSFWorkbook) {
    // do whatever
} else if (wb instanceof XSSFWorkbook) {
    // do whatever
}

The aforementioned approach will work.

But incase you are dealing with large files, there is a possibility that you will get File as ByteArayInputStream. In this case, the bellow approach shall work.

ByteArayInputStream bais = new ByteArrayInputStream(file.getData());

if(bais != null && POIFSFileSystem.hasPOIFSHeader(bais)) {
    System.out.println(".xls extention excel file");
    //do whatever
}
else if(bais != null && POIXMLDocument.hasOOXMLHeader(bais)) {
    System.out.println(".xlsx extention excel file");
    //do whatever
}
else {
    //wrong file format. throw exception.
}

Upvotes: 6

Paco Abato
Paco Abato

Reputation: 4065

This will do the work:

Workbook wb = WorkbookFactory.create(myExcelFile);

Then you can check the exact type created by the factory:

if (wb instanceof HSSFWorkbook) {
    // do whatever
} else if (wb instanceof SXSSFWorkbook) {
    // do whatever
} else if (wb instanceof XSSFWorkbook) {
    // do whatever
}

Anyway if you want to know the real type of the file before using it you can use Apache Tika.

Upvotes: 4

shauryachats
shauryachats

Reputation: 10385

You can let POI do the job for you, by using WorkbookFactory to automatically have the file extension detected opened for you.

Workbook w = WorkbookFactory.create(new File("hello.xls"));

Of course, you can use Apache Tika to detect the file format for you!

Upvotes: 3

anquegi
anquegi

Reputation: 11522

I woul recommend to use this FilenameUtils.getExtension from Apache Commons IO :

String ext = FilenameUtils.getExtension("path to the file");

Upvotes: 1

Related Questions