2

Here I want to extract the data from .xlsx file and for that I already add the poi jar and created the reference of fileInputStream

package demo;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class DemoExcel {

    public static void main(String[] args) throws Exception{
        File excel = new File("C:\\Users\\Devaditya\\Documents\\Book1.xlsx");
        FileInputStream fis = null;
        fis = new FileInputStream(excel);
        System.out.println(fis.toString());
        HSSFWorkbook wb = new HSSFWorkbook(fis);
        System.out.println(wb.toString());
        HSSFSheet sh = wb.getSheet("Data");
        System.out.println(sh.toString());
    }

}

Here i am getting the error:-

Exception in thread "main" java.io.IOException: Invalid header signature; read 0, expected -2226271756974174256
    at org.apache.poi.poifs.storage.HeaderBlockReader.<init>(HeaderBlockReader.java:88)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:83)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:210)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:191)
    at demo.DemoExcel.main(DemoExcel.java:23)
Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
Aditya Lodha
  • 21
  • 1
  • 2
  • 1
    This looks like a duplicate of [this](http://stackoverflow.com/questions/9696836/excel-read-error-invalid-header-signature-how-to-resolve), your question may be closed. – Yann Aug 22 '14 at 13:30

2 Answers2

5

Lets start with types of WorkBook.

HSSFWorkbook

This is old binary proprietary Excel format, know by the extension .xls.

XSSFWorkbook

This is the new XML Excel format, known by the extension .xlsx.

So, you are using the wrong class.

In fact it would be better not to use a specific class at all, let POI work out what you have. Use a WorkbookFactory:

final Workbook workbook = WorkbookFactory.create(excel);

This is:

  1. programming to the interface.
  2. robust to changes in the type of workbook read, as long a POI supports it
  3. faster and more efficient. POI can read the File piecemeal, when it needs to rather than having to slurp the whole workbook into memory.
  4. Doesn't have the memory leak that you have when you don't close() the FileInputStream.
Community
  • 1
  • 1
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • Just in case anyone did as me, I'll add that WorkbookFactory is not in poi library, but in poi-ooxml. I spent an hour figuring that one out. – jumps4fun Jan 16 '17 at 14:44
0

try to open the file in microsoft office Excel then a pop message will appear to inform you that that file you are trying to open isn't an excel file, and give you the choice to open it any way, so just open it and save it as excel file.

MoussabOr
  • 21
  • 7