Search code examples
javaexcelapacheapache-poi

Cannot read from Excel file using apache poi


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?


Solution

  • This may help you:--

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