当前位置:   article > 正文

org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException

org.apache.poi.openxml4j.exceptions.openxml4jruntimeexception: fail to save:

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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/459399
推荐阅读
相关标签
  

闽ICP备14008679号