apache poi indexoutofbound exception

时间:2015-03-15 14:14:58

标签: java apache-poi

  • Excel文件(test1.xlsx)
    姓名性别年龄辞职日期
    阿里M 20
    阿布M 25
    丝提˚F30个

  • 代码

    public class ReadExcel {
    
    public static ArrayList<String> record;
    
    public static void main(String[] args) throws FileNotFoundException, IOException {
    
     //---Read file---
    FileInputStream in = new FileInputStream("test1.xlsx");
    XSSFWorkbook workbook = new XSSFWorkbook(in);
    XSSFSheet spreadsheet = workbook.getSheetAt(0);
    XSSFRow row;
    Cell cell;
    
    Iterator<Row> rowIterator = spreadsheet.iterator();
    
    while(rowIterator.hasNext()){
        record = new ArrayList<String>();
        row = (XSSFRow)rowIterator.next();
    
        if(row.getRowNum()==0) {
            continue;
        }
    
         for(int k = 0; k < row.getLastCellNum();k++){
            cell = row.getCell(k, Row.CREATE_NULL_AS_BLANK);
        }
    
        Iterator<Cell> cellIterator = row.cellIterator();
    
        while(cellIterator.hasNext()){
                cell = cellIterator.next();
                cell.setCellType(Cell.CELL_TYPE_STRING); 
    
                switch(cell.getCellType()){
                    case Cell.CELL_TYPE_STRING:
                        record.add(cell.getStringCellValue());
                        System.out.print(cell.getStringCellValue());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        Double value = cell.getNumericCellValue();
                        Long longValue = value.longValue();
    
                        record.add(Double.toString(cell.getNumericCellValue()));
                        System.out.print(cell.getNumericCellValue());
                        break;
                }
            }   
            System.out.println();
    
            String name = record.get(0);
            String gender = record.get(1);
            String age = record.get(2);
            String dateLeave = record.get(3);  //[ERROR]
    
            System.out.println(name + gender + age + dateLeave);
            }
        }
    }
    

但是,从我上面的程序中,我得到了这个例外:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at ibguobform.ReadExcel.main(ReadExcel.java:66)
Java Result: 1

我犯了什么错误?

1 个答案:

答案 0 :(得分:3)

您的代码正在尝试引用仅包含三个元素的集合的第四个元素:

record.get(3)

由于只有三个元素,因此尝试引用第四个元素会产生错误。

为什么只有三个元素?

好吧,看看数据:

Ali     M     20
Abu     M     25
Siti    F     30

每行三个元素。

似乎正在发生的是代码动态检查最后一个&#34;元素&#34;:

for(int k = 0; k < row.getLastCellNum(); k++){
    cell = row.getCell(k, Row.CREATE_NULL_AS_BLANK);
}

似乎row.getLastCellNum()告诉代码只有三个单元格。 (因为,只有三个单元格中包含数据。)如果第四个单元格即使没有数据也有效,请在代码中明确注意总是使用四个元素:

for(int k = 0; k < 4; k++){
    cell = row.getCell(k, Row.CREATE_NULL_AS_BLANK);
}