0

I am trying to read from an excel file using the below code:

    File file = new File("/C:/behzad-data/trp.small.xlsx");
    String dataPath=file.getAbsolutePath();
    System.out.println(dataPath);
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));

    //XSSFWorkbook wb = new XSSFWorkbook(file);

    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell;

but it complains with:

org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
    at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:152)

so i have seen this, and make it like

XSSFWorkbook wb = new XSSFWorkbook(file);
 //   HSSFWorkbook wb = new HSSFWorkbook(fs);

but it complains with:

Type mismatch: cannot convert from XSSFSheet to HSSFSheet

How can i resolve both errors at the same time?

Jeff
  • 7,767
  • 28
  • 85
  • 138
  • If you are using an older version of excel create a copy in save it as a newer format. If the reverse is true, do the reverse. Now use this new copy file. – SedJ601 Apr 13 '17 at 19:57
  • i have tried `xlsx`, `xls` and `csv` none of them works – Jeff Apr 13 '17 at 20:04
  • [See this answer](http://stackoverflow.com/a/12495381/898274) – Kalenda Apr 13 '17 at 20:24
  • I have tired the `XSSFWorkbook` but, it leads to the error. or if u mean `factory` please write an answer – Jeff Apr 13 '17 at 20:37

1 Answers1

0

Why don't you use WorkbookFactorya nd only have to deal with one API for both types of workbooks? So with this new API, you don't have to prefex Sheet, Row, and so on with the file type, just use these classes like that.

File file = new File("C:\\behzad-data\\trp.small.xlsx");
Workbook wb = WorkbookFactory.create(file);

Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
    Row row = rows.next();
    // so on and so forth
}

Then just use wb as normal

Check the API docs for more info HERE

Note: These dependencies are needed for this to work

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.16-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.16-beta2</version>
</dependency>
Trash Can
  • 6,608
  • 5
  • 24
  • 38