Invalid header reading xls file

笑着哭i 提交于 2019-12-01 03:46:05

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

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.

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!