3

I am using Apache poi 3.8 for reading xls file, but i got exception:

        java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
        at org.apache.poi.poifs.storage.HeaderBlock.alertShortRead(HeaderBlock.java:226)
        at org.apache.poi.poifs.storage.HeaderBlock.readFirst512(HeaderBlock.java:207)
        at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
        at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:138)

used code sample:

     FileInputStream myInput = new FileInputStream(excelFilePathWithExtension);
     logger.debug("FileInputStream::"+myInput);

     POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
     logger.debug("POIFSFileSystem::"+myFileSystem);

     Workbook workbook = WorkbookFactory.create(myFileSystem);

please help me?

Sameek Mishra
  • 9,174
  • 31
  • 92
  • 118

4 Answers4

7

If we take a look at the HeaderBlocks class, we can see these blocks :

public HeaderBlock(InputStream stream) throws IOException {
    // Grab the first 512 bytes
    // (For 4096 sized blocks, the remaining 3584 bytes are zero)
    // Then, process the contents
    this(readFirst512(stream));
    ...
}

The constructor you used will read the first 512 bytes of your inputstream then call a private constructor.

And the readFirst512 method throw an exception if there is not enough bytes to read.

Also, the POI's document say that a POI file system structure starts starts with a header block of 512 bytes.

So... It seems that your file is not big enough for POI.

DayS
  • 1,561
  • 11
  • 15
3

Open in MS-Excel and save as different name. Try again.

Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
kfatih
  • 119
  • 1
  • 5
  • Even opening the file, doing a minor edit and saving works. In my case I edited one cell, saved then undo the changes, saved again and the exception was gone. Because it is a template file probably it got corrupted along the way. Excel can fix the problem POI crashes. Programmatically I will adapt my code to first copy the template file to a temporary directory and then do any operations. – Louis Papaloizou Jun 12 '17 at 15:09
0

if you place the files being read or written in different folder you may not get the error. Some default folders like 'Downloads' of Mozilla have restricted permissions, it seems.

ravi
  • 1
0

I also faced same problem even though the my excel file containing data. After upgrading my POI jar file version to poi-3.9.jar my issue resolved. Hope this will be helpful.

rajkumar chilukuri
  • 235
  • 1
  • 3
  • 8