8

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?

Gagravarr
  • 47,320
  • 10
  • 111
  • 156
Tim Tuckle
  • 1,372
  • 7
  • 21
  • 31

4 Answers4

13

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

evilReiko
  • 19,501
  • 24
  • 86
  • 102
  • First of all thanks for your help. I checked the page you've mentioned. Ok. I've added the code below in my pom.xml : org.apache.poi poi-contrib 3.7-beta3 However, in spite of that my Java class still cannot resolve XSSFWorkbook? There is no problem on HSSFWorkbook(); Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() }; – Tim Tuckle Nov 24 '10 at 20:43
  • 5
    XSSFWorkbook is in groupId: org.apache.poi, artifactId: poi-ooxml – rlovtang Nov 24 '10 at 21:48
6

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.");
}
CosmicGiant
  • 6,275
  • 5
  • 43
  • 58
1

Use the factory instead which handles both xssf and hssf

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

Workbook wb = WorkbookFactory.create(new File("file"))
Neuron
  • 5,141
  • 5
  • 38
  • 59
vingin
  • 11
  • 1
0

This worked for me:

    filePath = "C:\Users\user1\workspace\myproject\Excel.xlsx"
    String extension = FilenameUtils.getExtension(filePath);
    System.out.println(extension);