0

我正在尝试使用中读取xls文件javaapache poi 4.0.1

问题

当我尝试读取文件时,我遇到了以下异常

org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature;

完整的堆栈跟踪

org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x756F4E2C65707954, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
    at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:151)
    at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:117)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:294)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:401)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:382)
    at com.wild.animal.identifier.DataLoader.loadData(DataLoader.java:27)
    at com.wild.animal.identifier.WildAnimalSearch.main(WildAnimalSearch.java:6)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

当我尝试在 excel 中手动打开同一个文件时,出现以下对话框

在此处输入图像描述

问题

我做错了什么,我该如何解决?

代码

public static void loadData() {

    try {

        File dataFile = new File("Attachment_1551892122.xls");
        FileInputStream fins = new FileInputStream(dataFile);

        HSSFWorkbook workbook = new HSSFWorkbook(fins);
        HSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();

        Iterator<Cell> columnIterator;
        Row row;
        Cell column;

        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            columnIterator = row.cellIterator();

            while (columnIterator.hasNext()) {
                column = columnIterator.next();

                switch (column.getCellType()) {
                    case STRING:
                        System.out.print(column.getStringCellValue());
                        break;
                    case BOOLEAN:
                        System.out.print(column.getBooleanCellValue());
                        break;
                    case NUMERIC:
                        System.out.print(column.getNumericCellValue());
                        break;
                }
                System.out.print(" - ");
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
4

1 回答 1

0

正如@AxcelRichter 在评论中指出的那样,该文件不是 excel 文件,所以我创建了一个新的 excel 文件,将旧文件中的所有数据复制到新文件中。

尝试阅读新文件,它工作!

于 2019-03-07T19:58:31.423 回答