Java – Cannot read from Excel file using apache poi

apacheapache-poiexceljava

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?

Best Answer

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

Related Topic