尝试使用 jOpenDocument 获取 .ods 单元格时出现 IndexOutOfBoundException

IndexOutOfBoundException when trying trying to get a .ods cell with jOpenDocument

我的编码遇到了一些挑战。

File file = new File("template.ods");
Sheet sheet;
try {
    // load file
    sheet = SpreadSheet.createFromFile(file).getSheet("Certificate");
    System.out.println(file);
    System.out.println(sheet.getCellAt("A1").isEmpty());
    sheet.setValueAt("A1", 1, 1);;
    System.out.println(sheet.getCellAt(1, 1).getTextValue());
    sheet.getCellAt(2, 2).setValue("B2");
    sheet.getCellAt(3, 3).setValue("C3");
    sheet.getCellAt(4, 4).setValue("D4");
    // Save to file and open it.
    File outputFile = new File("fillingTest.ods");
    OOUtils.open(sheet.getSpreadSheet().saveAs(outputFile));

} catch (Exception e) {
    e.printStackTrace();
}

我开始了解 jOpenDocument-Library。我想用一些示例值填充现有的 OpenOffice-Spreadsheet-Template (template.ods)。 当运行以上代码时,控制台显示为:

template.ods
true

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at org.jopendocument.dom.spreadsheet.Table.getRow(Unknown Source)
    at org.jopendocument.dom.spreadsheet.Table.getImmutableCellAt(Unknown Source)
    at org.jopendocument.dom.spreadsheet.Table.getValueAt(Unknown Source)
    at org.jopendocument.dom.spreadsheet.Table.setValueAt(Unknown Source)
    at jOpenDocument.createDocument.main(createDocument.java:48)

"template.ods""true" 显示应用程序从目录中检索了文件并且 "true" 它可以读取空单元格。

但我不知道哪个数组抛出异常以及为什么它说 “未知来源”

行数组抛出异常。在设置单元格内容之前尝试使用 sheet.setRowCount() 添加更多行。

您可以使用 ensureRowCount,我认为这更合适:

sheet.ensureRowCount(row);