1

I have an excel file which has a couple of String datatype columns, one numeric column and one date column. Am using Apache POI to read the file. Below is how am handling the datatypes

Cell cell = sheet.getRow(i).getCell(j);

                if(cell!=null){
                    switch(cell.getCellType()){
                    case Cell.CELL_TYPE_STRING: 
                        cellValue = cell.getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
                        Date cellDate = cell.getDateCellValue();
                        cellValue = df.format(cellDate);
                        break;                          
                    case Cell.CELL_TYPE_BLANK:
                        break;
                    default :
                    }                       
                }

This works fine with String and date datatypes. But for numeric, it's converting the value to a date. I know it's because the handling has issues. Can you please advise on how to accommodate handling of both numeric and date datatypes?

Thanks, Sam.

1
  • 1
    Why not just use DataFormatter to turn the Cell into a String, and have it handle the complexity for you? Commented Dec 8, 2015 at 21:33

1 Answer 1

2

If you know what data types belong to each column, you don't even have to check cell type every time:

switch (columnIndex) {
    case 0:
    case 1:
    case 2: { 
       cellValue = cell.getStringCellValue();
       break; 
    }
    case 3: {
       Date cellDate = cell.getDateCellValue();
       // ...
       break;
    } 
    case 4: {
       cellValue = cell.getNumericCellValue();
       break;
    }    
}

If your column can contain both dates and numbers, you can try this

import org.apache.poi.ss.usermodel.DateUtil;

case Cell.CELL_TYPE_NUMERIC:
   if (DateUtil.isCellDateFormatted(cell)) {
      // your code for date handling
   } else {
      cellValue = cell.getNumericCellValue();
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Adam !! Worked like a charm :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.