Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring batch excel extension

to read an excel file composed of 17 columns and a single line I used the excel extension Spring batch. the problem is that when I run the application, it gets to read the first 9 columns after this index I get an error :

Caused by: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 9
at org.springframework.batch.item.excel.support.rowset.DefaultRowSet.getColumnValue(DefaultRowSet.java:71) ~[classes/:na]
at com.example.demo.mappers.UtilisateurExcelRowMapper.mapRow(UtilisateurExcelRowMapper.java:23) ~[classes/:na]
at com.example.demo.mappers.UtilisateurExcelRowMapper.mapRow(UtilisateurExcelRowMapper.java:1) ~[classes/:na]
at org.springframework.batch.item.excel.AbstractExcelItemReader.doRead(AbstractExcelItemReader.java:70) ~[classes/:na]
... 50 common frames omitted

below my code

@Bean
PoiItemReader<Utilisateur> excelUtilisateurReader() {
    PoiItemReader<Utilisateur> reader = new PoiItemReader<Utilisateur>();
    reader.setLinesToSkip(5);
    reader.setMaxItemCount(1);
    reader.setRowMapper(excelRowMapper());
    return reader;
}

note that my file contains 17 columns all filled

like image 814
Eng pro Avatar asked Nov 16 '22 22:11

Eng pro


1 Answers

It seems to be the problem of spring-batch-excel library. For some reason, it does not take into account empty cells, e.g: enter image description here In RowMapper class, RowSet object for 3 and 4 rows will contain only 4 items (and you will get ArrayIndexOutOfBoundsException), but RowSet object for 5 row - 8 items.

I've fixed it by adding validation in RowMapper:

public class MyRowMapper implements RowMapper<MyDto> {

    @Override
    public MyDto mapRow(RowSet rowSet) throws Exception {
        MyDto dto = new MyDto();

        dto.setStart(checkAndGetCell(rowSet, 2));
        dto.setEnd(checkAndGetCell(rowSet, 3));
        dto.setStatus(checkAndGetCell(rowSet, 6));

        return dto;
    }

    private String checkAndGetCell(RowSet rowSet, Integer index) {
        return  rowSet.getProperties().size() > index ? rowSet.getColumnValue(index) : "";
    }
}
like image 69
Andriy Budzinskyy Avatar answered Dec 14 '22 22:12

Andriy Budzinskyy