1

I am using Apache POI to read an Excel file having many columns. I have a POJO in which there is a field for each column in Excel sheet.

How do I populate my POJO with values from Excel achieving minimum cyclomatic complexity?

I had implemented really crude approach of having switch..case for populating my POJO, but this results in tight coupling and gives rise to high cyclomatic complexity, giving below my implementation for reference (this is I feel very dirty implementation) :

    // Iterate over cells in a row
    for (Cell cell : row) {
        cellValue = getCellValue(cell);

        if (cellValue == null) {
        continue;
        }

        // Populate model
        data = populateModel(data, cell.getColumnIndex(), cellValue);
    }

called method:

    /*
     * Populates pojo
     */
    private MyData populateModel(MyData data, int columnIndex, Object cellValue) {
    switch (columnIndex) {
        case 0:
        data.setAccount((long) cellValue);
        break;
        case 1:
        data.setDocNumber((long) cellValue);
        break;
        case 2:
        data.setType((String) cellValue);
        break;
        // more cases for subsequent excel columns
        default:
        // do nothing
       }
    return data;
    }
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62
  • 1
    check out data unmarshalling. Also you can convert the excel file to XML and use something like JAXB to unmarshall the data to POJOs. – Rafael Oct 10 '17 at 01:42
  • If you don't have calculations in Excel , convert to CSV and use Smooks [link]http://www.smooks.org/guide[link] tools for data mapping, its high performing and mapping logic will be configurable – Abin Manathoor Devasia Oct 10 '17 at 01:47
  • Why not hand over your `populateModel` the whole [Row](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html)? Then you can get the appropriate `Cell`s having the appropriate column indexes using [Row.getCell](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell-int-). – Axel Richter Oct 10 '17 at 03:45

0 Answers0