我正在尝试使用 Java 解析以 .csv 结尾的 excel 文件。经过一番研究,我下载并安装了 ApachePOI 库。但是,每次我尝试打开要解析的 excel 文件时,都会出现以下错误:
Exception in thread "main" java.io.IOException: Invalid header signature; read 0x4E2C53454C494D53, expected 0xE11AB1A1E011CFD0
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:140)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:138)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:322)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:303)
at excellibrarycreation.ExcelFileProcesser.processFile(ExcelFileProcesser.java:40)
at excellibrarycreation.ExcelLibraryCreation.main(ExcelLibraryCreation.java:24)
Java Result: 1
我在 Stack Overflow 和其他网站上对这个问题进行了更多研究,但答案让我非常困惑,因为我从未听说过 OLE2 文件和标头签名之类的东西。如果有人可以简单地解释这个问题,我将不胜感激。这是我的代码:
public void processFile(File excelWorkbook) throws FileNotFoundException, IOException{
System.out.println("Processing file...");
FileInputStream fileInputStream = new FileInputStream(excelWorkbook);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = firstSheet.iterator();
while (rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
org.apache.poi.ss.usermodel.Cell cell = cellIterator.next();
switch(cell.getCellType()){
case Cell.CELL_TYPE_BOOLEAN:
System.out.println("Cell type is boolean: "+cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Cell type is numeric: "+cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Cell type is String: "+cell.getStringCellValue());
break;
}
System.out.println("");
}
fileInputStream.close();
}
}