gpt4 book ai didi

java - 为什么我使用 POI 读取 Excel 2007 失败?

转载 作者:行者123 更新时间:2023-11-29 05:54:46 25 4
gpt4 key购买 nike

当我尝试初始化一个 Workbook 对象时,我总是得到这个错误:

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 (eg XSSF instead of HSSF)

但我是按照办公室示例来做的,下面是我的代码:

File inputFile = new File(inputFileName); 
InputStream is = new FileInputStream(inputFile);
Workbook wb = new XSSFWorkbook(is);

异常发生在代码行:

Workbook wb = new XSSFWorkbook(is);

这是 POI jar,包括:

poi-3.8-20120326.jar  
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
xmlbeans-2.3.0.jar

有大佬可以指教一下吗?一个显示如何阅读完整的 Excel 2007 文档的示例将不胜感激。提前致谢!

最佳答案

我假设您已经重新检查过您的原始文件确实是 Office 2007+XML 格式,对吧?

编辑:

然后,如果您确定格式没问题,并且使用 WorkbookFactory.create 对您有效,您可以在此类方法的代码中找到答案:

   /**
* Creates the appropriate HSSFWorkbook / XSSFWorkbook from
* the given InputStream.
* Your input stream MUST either support mark/reset, or
* be wrapped as a {@link PushbackInputStream}!
*/
public static Workbook create(InputStream inp) throws IOException, InvalidFormatException {
// If clearly doesn't do mark/reset, wrap up
if(! inp.markSupported()) {
inp = new PushbackInputStream(inp, 8);
}

if(POIFSFileSystem.hasPOIFSHeader(inp)) {
return new HSSFWorkbook(inp);
}
if(POIXMLDocument.hasOOXMLHeader(inp)) {
return new XSSFWorkbook(OPCPackage.open(inp));
}
throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}

这是您缺少的部分:new XSSFWorkbook(OPCPackage.open(inp))

关于java - 为什么我使用 POI 读取 Excel 2007 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12593752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com