1
votes

This is the code that I a have written.

import java.util.*;
import java.lang.*;
import java.io.*;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        File inputFile = new File("./test.xlsx");
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell;
        Row row;
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()){
            row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()){
                cell = cellIterator.next();
                System.out.println(cell.getStringCellValue());
            }
        }
    }
}

This is the error that I am getting.

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)

Question: What am I doing wrong?

3

3 Answers

3
votes

As Rahul said, you are using HSSF part which is used to fetch info from old excel i.e. .xls (before 2007) format.

Workbook wb = WorkbookFactory.create(new File("/path/to/your/excel/file"));
    Sheet mySheet = wb.getSheetAt(0);
    Iterator<Row> rowIter = mySheet.rowIterator();
    System.out.println(mySheet.getRow(1).getCell(0));

Please try to convert to above, it will work for both .xls and .xlsx

2
votes

This may help you:--

file = new File("/yourFile.xlsx");
workBook = WorkbookFactory.create(file);    
sheet  = workBook.getSheetAt(sheetNumber);
1
votes

You are trying to access .xlsx file with HSSFWorkbook, you will need to use XSSFWorkbook instead of HSSFWorkbook. With HSSFWorkbook we can access .xls files.

For reference you can read POI