Rachel
Rachel

Reputation: 103397

How to add multiple different columns of excel using Apache POI & Java

I need to generate CodeKey that is combination of two columns of excel value and values in those columns can be Boolean, String, Numeric or combination of all of those.

Now I can go through if/else loop and check for every condition but what would be an efficient way of doing this.

For Example:

If i have ExCode = 7V and PrCode = A: then my CodeKey should be 7VA:

 ExCode  PrCode
 6D:     A:
 6R      TR
 7V      6K

And all i want to do is generate CodeKey as 6D:A:, 6RTR and 7V6K respectively.

Don't want to do something like:

 if(ExCodeCellValue.getCellType() == Cell.CELL_TYPE_STRING &&
           PrCodeCellValue.getCellType() == Cell.CELL_TYPE_STRING){
            System.out.println("Combined String Values: "+ExCodeCellValue.getStringValue()+PrCodeCellValue.getStringValue());
        }

As there would be lots of if/else unnecessary stuffs to generate codeKey, any other efficient solution of doing this or is there any api in POI that would be useful for this case?

Upvotes: 0

Views: 2399

Answers (1)

Gagravarr
Gagravarr

Reputation: 48326

I think you should be able to use DataFormatter.formatCellValue(cell) which will give you a string that matches what Excel shows for a cell.

With that, you could would look something like (Assuming the ExCode is the 3rd column, PrCode in the 4th)

// Do this once
DataFormatter formatter = new DataFormatter();

// Once per row
for (Row row : sheet) {
  String exCode = formatter.formatCellValue( row.getCell(2) );
  String prCode = formatter.formatCellValue( row.getCell(3) );

  Cell code = row.createCell(4, Cell.CELL_TYPE_STRING);
  code.setCellValue(exCode + prCode);
}

Upvotes: 1

Related Questions