我正在尝试通过 apache POI 编辑 xls 文件,但在调用 workbook.write(fileOutpuStream) 时,出现以下错误:
ERROR [2018-01-16 20:33:50,817] java.lang.ArrayIndexOutOfBoundsException: 1
at org.apache.poi.xssf.usermodel.XSSFTable.setCellReferences(XSSFTable.java:294)
at org.apache.poi.xssf.usermodel.XSSFTable.getStartCellReference(XSSFTable.java:266)
at org.apache.poi.xssf.usermodel.XSSFTable.updateHeaders(XSSFTable.java:347)
at org.apache.poi.xssf.usermodel.XSSFTable.writeTo(XSSFTable.java:93)
at org.apache.poi.xssf.usermodel.XSSFTable.commit(XSSFTable.java:104)
at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:414)
at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:419)
at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:419)
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:242)
我的代码的一些行是:
Workbook workbook = new XSSFWorkbook(fileInputStream)
Sheet firstSheet = workbook.getSheetAt(0);
/* iterate through rows and columns, write at the last column (fixed number) */
fileInputSream.close()
FileOutputStream fileOut = new FileOutputStream(localFile);
workbook.write(fileOut);
fileOut.close()
类似的代码之前对我有用,所以我不知道这有什么问题。我真的被困在这个问题上了。
编辑:
我得到了 jontro 指出的部分。 它确实只找到我的工作表的起始引用。
我有一个像这样的Excel:
id | name | result
1 | first |
2 | second |
我正在迭代行,并在系统中创建用户,如果创建成功,我会在结果列中写入 true (false)。由于 xlsx 是通过谷歌电子表格创建的,所以我没有结束行,所以如果我发现空名称,我就会跳出行迭代器。然后执行上面写的注释下面的代码部分。
编辑2:
InputStream is = new FileInputStream(localFile);
try (Workbook workbook = new XSSFWorkbook(is)) {
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
Data data = new Data(row.cellIterator());
//do something with data
data.getCell().setCellValue("processed");
}
FileOutputStream fileOut = new FileOutputStream(localFile);
workbook.write(fileOut); //fails here
fileOut.close();
} catch (Exception e) {//print
}
public class Data {
Data (Iterator<Cell> iterator) {
Cell cell = iterator.next();
this.var1 = cell.getStringCellValue();
cell = iterator.next();
this.var2 = cell.getStringValue();
....
this.cell = iterator.next(); //this is for saying processed
}
我开始同意 Axel 的评论,即这与 Google 电子表格创建 Table 对象有关。我有一个类似的代码,其中有一个不同的数据类,并且有效!我双重验证了所有内容,没有任何不同。
最佳答案
通过查看XSSFTable.java的主干中的代码我们可以看到下面的代码
private void setCellReferences() {
String ref = ctTable.getRef();
if (ref != null) {
String[] boundaries = ref.split(":", 2);
String from = boundaries[0];
String to = boundaries[1];
startCellReference = new CellReference(from);
endCellReference = new CellReference(to);
}
}
在以下行中抛出 ArrayIndexOutOfBoundsException
String to =boundary[1];
单元格引用的格式应为 A1:B3
或类似形式。由于您没有发布循环,因此很难准确说出导致此错误的原因。检查您是否创建了不完整的单元格范围
关于java - Apache POI XSFTable.java :294 arrayindex out of bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289914/