在学习导出功能时使用
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);