无法写入Excel文件,获取OpenXML4JRuntimeException

时间:2018-08-01 10:45:11

标签: java apache-poi

我正在尝试从excel读取测试数据并用测试结果更新同一张纸。问题在于,在第二次迭代中,Eclipse IDE会生成一个异常,并且状态也不会在excel中更新。文件也似乎已损坏。这是代码:

File src = new File("C:\\Users\\Sajid\\Desktop\\SeleniumData.xlsx");
FileOutputStream fos = new FileOutputStream(src, true);
FileInputStream fis = new FileInputStream(src);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);

for (int i = 1; i <= sheet.getLastRowNum(); i++)
{
    // Import data for Email.
    cell = sheet.getRow(i).getCell(0);
    cell.setCellType(Cell.CELL_TYPE_STRING);
    new WebDriverWait(driver, 50).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"email\"]")));
    driver.findElement(By.xpath("//*[@id=\"email\"]")).sendKeys(cell.getStringCellValue());

    String message = "Pass";
    sheet.getRow(i).createCell(15).setCellValue(message);
    workbook.write(fos);
}

例外:

  

org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException:保存失败:保存包时发生错误:/docProps/app.xml部件无法通过marshaller org.apache.poi保存在流中。 openxml4j.opc.internal.marshallers.DefaultMarshaller@2e62e227

更新代码

File src = new File("C:\\Users\\Sajid\\Desktop\\SeleniumData.xlsx");
FileOutputStream fos = new FileOutputStream(src, true);
FileInputStream fis = new FileInputStream(src);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);

for (int i = 1; i <= sheet.getLastRowNum(); i++)
{
    // Import data for Email.
    cell = sheet.getRow(i).getCell(0);
    cell.setCellType(Cell.CELL_TYPE_STRING);

    String message = "Pass";
    sheet.getRow(i).createCell(15).setCellValue(message);
    workbook.write(fos);

    driver.findElement(By.cssSelector("b.hidden-xs")).click();
    Thread.sleep(500);
    driver.findElement(By.cssSelector("a.sign-out")).click();
    Thread.sleep(1000);
}

fos.close();
fis.close();

但是我得到 cell.setCellType(Cell.CELL_TYPE_STRING); 行的空指针异常

java.lang.NullPointerException

2 个答案:

答案 0 :(得分:1)

您在这篇文章OpenXML4JRuntimeException: Fail to save上大笑了吗?

有两种解决方案可能对您有所帮助:

1-您要多次打开文件,因此在打开文件之前,请检查文件是否已关闭。

2-您的jar文件的版本将被覆盖,因此请在pom.xml中添加依赖项:

<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-dom</artifactId>
<version>1.8</version>
</dependency>

答案 1 :(得分:1)

如果不是随机访问文件,则无法同时打开文件进行输入和输出。

此外,输出不应追加到现有文件,而应替换该文件。

还要写一次工作簿。

FileInputStream fis = new FileInputStream(src);
workbook = new XSSFWorkbook(fis);
fis.close();

FileOutputStream fos = new FileOutputStream(src); // Without append true.
...
workbook.write(fos);
fos.close();