Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache POI, using both XSSF and HSSF

I have a problem with Apache POI project.

I failed to use XSSF and HSSF in the "Same Java Class". Which jar should I download or which artifact should I get add into maven?

I want to handle both xls and xlsx files at the same time. When I get excel version error, I will change the XSSF to HSSF or HSSF to XSSF.

How can I do this?

like image 876
Tim Tuckle Avatar asked Nov 24 '10 12:11

Tim Tuckle


2 Answers

Instead of doing that, try using the new release of Apache POI 3.7, it has SS package which handles both HSSF and XSSF without worrying about type

Details here: http://poi.apache.org/spreadsheet/index.html

like image 126
evilReiko Avatar answered Oct 21 '22 10:10

evilReiko


Aside from the "standard" SS package solution, you can also simply use an if statement to correctly load the right workbook format into an Workbook interface object, like so:

Workbook workbook; //<-Interface, accepts both HSSF and XSSF.
File file = new File("YourExcelFile.xlsx");
if (FileUtils.getFileExt(file).equalsIgnoreCase("xls")) {
  workbook = new HSSFWorkbook(new FileInputStream(file));
} else if (FileUtils.getFileExt(file).equalsIgnoreCase("xlsx")) {
  workbook = new XSSFWorkbook(new FileInputStream(file));
} else {
  throw new IllegalArgumentException("Received file does not have a standard excel extension.");
}
like image 27
XenoRo Avatar answered Oct 21 '22 11:10

XenoRo