[英]Java POI the supplied data appears to be in the Office 2007+ XML
我收到此错误:
org.apache.poi.poifs.filesystem.OfficeXmlFileException:提供的数据似乎在 Office 2007+ XML 中。 您正在调用处理 OLE2 Office 文档的 POI 部分。 您需要调用 POI 的不同部分来处理此数据(例如 XSSF 而不是 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 无法解析为类型
根据Apache POI Quick Guide , POIFSFileSystem
(或类似的, 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 文件一起使用,但是当我尝试处理使用密码加密/保护的文件时出现此错误。
删除密码后,一切都按预期进行。
实际上没有 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.