有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

excel Java POI提供的数据似乎位于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)

我阅读了Trow 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


共 (3) 个答案

  1. # 1 楼答案

    实际上没有OPC包, 我正在使用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;
    
  2. # 2 楼答案

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

    相当于。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或an。xlsx:

    // or "file.xlsx"
    Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
    
  3. # 3 楼答案

    我将XSSF与xlsx文件一起使用,但当我试图处理一个用密码加密/保护的文件时,出现了这个错误

    一旦我删除了密码,一切正常