使用Apache POI 导入导出时出现You need to call a different part of POI to process this data (eg XSSF instead of HSSF)Java异常

问题复现

在学习导出功能时使用HSSFWorkbook导出了一个xxx.xlsx格式的文件,然后用XSSFWorkbook的读取方式来拿文件去导入时出现了这个bug

这是当时做导出测试代码

Workbook wb = new HSSFWorkbook();
CreationHelper creationHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("dsad");
try (OutputStream fileOut = new FileOutputStream("MyExcel.xlsx")) {
   wb.write(fileOut);
}

然后那这个去做导入操作,因为导出的格式为.xlsx就使用OPCPackage去获取文件

OPCPackage pkg =  OPCPackage.open("MyExcel.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(pkg);
Sheet newSheet = wb.getSheet("new sheet");
Row row = newSheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell.getStringCellValue());
pkg.close();

然后在执行导入时就报了这个错误

org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format.
You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI
 to process this data (eg HSSF instead of XSSF)

问题分析

HSSFWorkbook对应的是xls,XSSFWorkbook对应的是xlsx,导入导出时所使用的Workbook对象要一致。如果使用xls就都用HSSFWorkbook,使用xlsx就都用XSSFWorkbook

问题解决

// 将导出新建的 HSSFWorkbook 换成 XSSFWorkbook
Workbook wb = new XSSFWorkbook();
CreationHelper creationHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("dsad");
try (OutputStream fileOut = new FileOutputStream("MyExcel.xlsx")) {
   wb.write(fileOut);
}
posted @ 2023-12-14 14:03  Justin99  阅读(1384)  评论(0编辑  收藏  举报