org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package : The part /docProps/app.xml failed to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller@2b2d97a
如果要针对同一个excel文件进行多次读写,在根据这个文件再次创建Workbook 对象的时候一定要使用流,而不是使用File,也就是说使用构造方式WorkbookFactory.create(inputStream)
代替WorkbookFactory.create(file)
,否则就会导致OpenXML4JRuntimeException
异常(如上所示)、
// 2.创建或使用原来的excel文件
Workbook workbook = null;
try {
File file = .. // 要读取的文件;
if (file.exists() && file.canRead() && file.canWrite() && file.length() != 0) {
try (InputStream inputStream = new FileInputStream(file)) {
// WorkbookFactory.create(file) 导致异常 org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package
// 第二次无法再次写文件 必须通过流打开文件
// workbook = WorkbookFactory.create(file);
workbook = WorkbookFactory.create(inputStream);
}
}
// ...... 此处省去针对workbook的操作
try (FileOutputStream outputStream = new FileOutputStream(new File(excelFileLoc))) {
workbook.write(outputStream);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(workbook);
}
}