Java POI 提供的数据似乎在 Office 2007+ XML

Java POI the supplied data appears to be in the Office 2007+ XML

我收到这个错误:

org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (e.g. XSSF instead of HSSF)

我读了 throw Google,我发现我需要使用 XSSF 而不是 HSSF,因为我的 Excel 文件是 xlsx,但是正如你在我的 maven 中看到的,我已经在使用 xlsx .请问我哪里出错了?

<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.13-beta1</version>
    </dependency> 

产生异常的代码是:

POIFSFileSystem fs;

            fs = new POIFSFileSystem(new FileInputStream(getFilePath()));

我的新密码

public void getBColum() {
    try {
        OPCPackage fs;

        fs = new OPCPackage.open(new File(getFilePath()));

        XSSFWorkbook wb = new XSSFWorkbook(fs);
        XSSFSheet sheet = wb.getSheet("Master column name - Used Car");
        XSSFRow row;
        CellReference cr = new CellReference("A1");
        row = sheet.getRow(cr.getCol());
        System.out.println(row.getCell(3));
    } catch (FileNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("How can this error be possible? we should have already thrown an exception in the construction");
        }
    } catch (IOException e) {
        logger.error(String.format("Exception in reading the file: %s",
                e.getMessage()));
    }
}

我在 new oPCPackage.open 中有一个编译错误,即:

OPCPackage.open cannot be resolved to a type

根据 Apache POI Quick GuidePOIFSFileSystem(或类似地,NPOIFSFileSystem)仅与 .xls(Excel 版本到 2003)文档一起使用。

.xlsx 文档 (Excel 2007+) 的等价物是 OPCPackage.

OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));

您可以从 OPCPackage:

创建一个 XSSFWorkbook
XSSFWorkbook wb = new XSSFWorkbook(pkg);

或者您可以直接创建它:

XSSFWorkbook wb = new XSSFWorkbook(new File("file.xlsx"));

通常最好使用 File 而不是 InputStream 创建工作簿以节省内存。

此外,如果您想要的代码不关心它是 .xls 还是 .xlsx:

// or "file.xlsx"
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));

我将 XSSF 与 xlsx 文件一起使用,但是当我尝试处理 encrypted/protected 带有密码的文件时出现此错误。

删除密码后,一切正常。

实际上没有 OPCPackage, 我正在使用 https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml/3.5-beta5 所以你必须:

import org.apache.poi.openxml4j.opc.Package;
....
Package fs = Package.open(new ByteArrayInputStream(container.getContent()));
            XSSFWorkbook wb = new XSSFWorkbook(fs);
            XSSFSheet sheet = wb.getSheetAt(0);
            XSSFRow row;
            XSSFCell cell;