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....
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.
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));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With