java NotOLE2FileException: 无效的标头签名;读取 0x0000000000000000,预期为 0xE11AB1A1E011CFD0 - 文件似乎不是有效的 OLE2 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36119130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NotOLE2FileException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0 - file appears not to be a valid OLE2 document
提问by Jay Rathod
try {
File file = new File("file4.xls");
if (!file.exists()) file.createNewFile();
FileInputStream fis = new FileInputStream(file);
POIFSFileSystem fileSystem = new POIFSFileSystem(fis);
// FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
//Sheet sheet = workbook.createSheet("sheet0");
Sheet sheet = workbook.getSheet("sheet1");
sheet.createRow(0).createCell(0).setCellValue("HelloWorld");
Cell cell = sheet.createRow(1).createCell(0);
cell.setCellValue("Value_1_1");
fis.close();
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
I am trying to create simple excel file using java. I am getting above mentioned error.
我正在尝试使用 java 创建简单的 excel 文件。我收到上述错误。
回答by Gagravarr
Your problem is this line here:
你的问题是这里的这一行:
if (!file.exists()) file.createNewFile();
That creates a brand new 0 byte file, which is not a valid Excel file. That's why POI objects.
这会创建一个全新的 0 字节文件,该文件不是有效的 Excel 文件。这就是 POI 对象的原因。
Also, you're using an old version of Apache POI. Newer ones give a more helpful exception if you're silly enough to ask them to read a zero byte file
此外,您使用的是旧版本的 Apache POI。如果您足够愚蠢要求他们读取零字节文件,则较新的会提供更有用的例外
Taking account of the advice on Files vs InputStreams, but noting you're doing an in-place write which isn't yet fully supported on an opened File, change your code to be more like:
考虑到有关 Files vs InputStreams的建议,但注意到您正在执行在打开的文件上尚不完全支持的就地写入,请将您的代码更改为更像:
Workbook workbook = null;
File file = new File("file4.xls");
if (!file.exists()) {
if (file.toString().endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
} else {
workbook = new HSSFWorkbook();
}
} else {
workbook = WorkbookFactory.create(new FileInputStream(file));
}
That will work for both .xls
and .xlsx
files, and avoids your errro
这将适用于.xls
和.xlsx
文件,并避免您的错误
Though you really ought to upgrade your version of Apache POI too...
虽然你真的应该升级你的 Apache POI 版本......
回答by Mushfiq Nagori
Open the file once. Check your file once on click save as. If it is generated from HTML it will show as Web page(*.htm , .html) below drop down to the file. You can save as Excel 97-2003 Workbook (.xls) and retry to read from code. It worked in my case.
打开文件一次。单击另存为后检查您的文件。如果它是从 HTML 生成的,它将显示为网页 (*.htm , .html) 下面的下拉菜单。您可以另存为 Excel 97-2003 工作簿 (.xls)并重试读取代码。它在我的情况下有效。