Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to read both .xls and .xlsx files using Apache POI?

I need to create a method that can read both xls and xlsx files. According to my research, HSSF is used to read xls and XSSF to read xlsx. Is there a part of the Apache POI I can use to read both files? I also came across the ss.usermodel but found no sufficient codes that will entertain both xls and xlsx....

like image 556
TOMAS DEL CASTILLO Avatar asked Oct 02 '13 04:10

TOMAS DEL CASTILLO


People also ask

Does Apache POI support xls?

The Apache POI library supports both . xls and . xlsx files and is a more complex library than other Java libraries for working with Excel files.


2 Answers

Yes, there's a new set of interfaces provided by POI that work with both types.

Use the WorkbookFactory.create() method to get a Workbook: http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/WorkbookFactory.html

You can check for excel files without relying on file extensions (which are unreliable - many csv files have xls extensions for example but cannot be parsed by POI) using the following:

//simple way to check for both types of excel files
public boolean isExcel(InputStream i) throws IOException{
    return (POIFSFileSystem.hasPOIFSHeader(i) || POIXMLDocument.hasOOXMLHeader(i));
}
like image 54
tom Avatar answered Oct 12 '22 04:10

tom


I haven't had much exp with Apache POI, but as far as i know if you refer to a workbook by class "Workbook" then you can read and write both xls & xlsx.

All you have to do is when creating object write

for .xls-

Workbook wb = new HSSFWorkbook();

for .xlsx-

Workbook wb = new XSSFWorkbook();

you can pass a parameter for file type and create the WorkBook object accordingly using If statement.

like image 45
Sumit Gupta Avatar answered Oct 12 '22 03:10

Sumit Gupta