Invalid header reading xls file

前端 未结 3 1724
独厮守ぢ
独厮守ぢ 2021-01-12 06:33

I am reading one excel file on my local system. I am using POI jar Version 3.7, but getting error Invalid header signature; read -2300849302551019537 or in Hex 0xE011BDBFEF

相关标签:
3条回答
  • 2021-01-12 07:03

    That exception is telling you that your file isn't a valid OLE2-based .xls file.

    Being able to open the file in Excel is no real guide - Excel will happily open any file it knows about no matter what the extension is on it. If you take a .csv file and rename it to .xls, Excel will still open it, but the renaming hasn't magically made it be in the .xls format so POI won't open it for you.

    If you open the file in Excel and do Save-As, it'll let you write it out as a real Excel file. If you want to know what file it really is, try using Apache Tika - the Tika CLI with --detect ought to be able to tell you

    .

    How can I be sure it's not a valid file? If you look at the OLE2 file format specification doc from Microsoft, and head to section 2.2 you'll see the following:

    Header Signature (8 bytes): Identification signature for the compound file structure, and MUST be set to the value 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1.

    Flip those bytes round (OLE2 is little endian) and you get 0xE11AB1A1E011CFD0, the magic number from the exception. Your file doesn't start with that magic number, as so really isn't a valid OLE2 document, and hence POI gives you that exception.

    0 讨论(0)
  • 2021-01-12 07:09

    Just an idee, if you using maven make sure in the resource tag filtering is set to false. Otherwise maven tends to corrupt xls files in the copying phase

    0 讨论(0)
  • 2021-01-12 07:13

    If your project is maven project, the following code may help:

    /**
     * Get input stream of excel.
     * <p>
     *     Get excel from src dir instead of target dir to avoid causing POI header exception.
     * </p>
     * @param fileName file in dir PROJECT_PATH/src/test/resources/excel/ , proceeding '/' is not needed.
     * @return
     */
    private static InputStream getExcelInputStream(String fileName){
        InputStream inputStream = null;
        try{
            inputStream = new FileInputStream(getProjectPath() + "/src/test/resources/excel/" + fileName);
        }catch (URISyntaxException uriE){
            uriE.printStackTrace();
        }catch (FileNotFoundException fileE){
            fileE.printStackTrace();
        }
        return inputStream;
    }
    
    private static String getProjectPath() throws URISyntaxException{
        URL url = YourServiceImplTest.class.getResource("/");
        Path path = Paths.get(url.toURI());
        Path subPath = path.subpath(0, path.getNameCount() -2);
        return "/" + subPath.toString();
    }
    
    0 讨论(0)
提交回复
热议问题