org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: 保存失败

13

我遇到了 org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save:an error occurs while saving the package : The part /docProps/app.xml fail to be saved in the stream with marshaller <br/> org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller@7c81475b 的问题。

在每个测试场景执行完成后,试图将每个测试场景的结果(PASS或FAIL)写入Excel表格(.xlsx)时发生异常。我为此编写了以下两个不同的模块。

请告诉我问题出在哪里以及如何解决它。

//Method for writing results into Report
 public void putResultstoReport(String values[])
 {
      int j=NoofTimesExecuted;
      NoofTimesExecuted++;
      XSSFRow row = sheet.createRow(j);
      for(int i=0;i<values.length;i++)
      {
           XSSFCell cell = row.createCell(i);
           cell.setCellValue(values[i]);
      }
      try {
           System.out.println("Times:"+NoofTimesExecuted);
           wb.write(fileOut);
      }
      //fileOut.flush();
      //fileOut.close();
      }
      catch(Exception e) {
           System.out.println("Exception at closing opened Report :"+e);
      }

//Method for Creating the Excelt Report
 public void createReport()
 {
      String FileLocation = getProperty("WorkSpace")+"//SCH_Registration//OutPut//TestResults.xlsx";
      try {
           fileOut = new FileOutputStream(FileLocation);
           String sheetName = "TestResults"; //name of sheet
           wb = new XSSFWorkbook();
           sheet = wb.createSheet(sheetName);
           fileOut.flush();
           fileOut.close();
      }
      catch(Exception e)
      {
           System.out.println("Exception at Create Report file:"+e);
      }
}

错误信息甚至不是好的英语。如果有人能尝试,请在这里回答问题,我会给予奖励。https://dev59.com/2Hvaa4cB1Zd3GeqPBUld - David Williams
6个回答

6

我也遇到了这个错误。

我发现我的错误是因为我多次打开同一个文件/工作簿。

因此,在尝试关闭之前,请确保只打开一次。


5

如果超时会发生这种情况。我有可适用于小数据集的代码,但在大数据集上会抛出此错误。


你是如何解决这个问题的?你是如何为大数据集生成Excel的?这是客户端错误还是服务器端错误?请帮帮我,我觉得我遇到了同样的问题。 - Hari
1
在我的情况下,这是由于我的请求的 HTTP 超时关闭了输出流。花了我一点时间才发现,因为我的 HTTP 请求通过一个代理,它是超时的那个。一个可能的解决方案是避免发送同步请求进行大文件导出,而是使用 WebSocket 来告诉前端导出已经完成并准备好请求下载。 - Eva

5

我今天遇到了这个问题并已经解决了。

问题出在putResultstoReport()函数里。

你不能在循环中使用wb.write(fileOut);

解决方法:

先调用putResultstoReport();,然后再调用wb.write(fileOut);


1
我遇到了同样的问题。当我缩短输出 Excel 文件名时,问题消失了。

节省了无数的时间,这对我来说是事实。 - lpkej

0

我曾经遇到过类似的问题。 最终我找到了原因,是下面这个jar文件的版本被覆盖了。

  org.apache.xmlgraphics:batik-dom

因此,我添加了以下依赖项,现在它可以正常工作了。
<dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>batik-dom</artifactId>
    <version>1.8</version>
</dependency>

这个 jar 包含 xalan 的依赖项。 要生成报告,需要 xalan


0

我曾经遇到过同样的问题,即在上一个请求完成之前,用户刷新页面并再次发送请求。为了避免名称冲突,请在创建名称时使用毫秒级别的时间戳。通过更新名称创建代码来解决上述问题。

       String sheetName="projectName"+System.currentTimeMillis() + ".xlsx"
       FileOutputStream fileOut = new FileOutputStream(sheetName);
       workbook.write(fileOut);
       fileOut.close();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接