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?


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.


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.
}

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!

链接地址: http://www.djcxy.com/p/45450.html

上一篇: Word / Excel文件从PHP下载时损坏

下一篇: 用Apache POI打开xls和xlsx