V
V
vitya_brodov2021-10-04 13:36:35
Java
vitya_brodov, 2021-10-04 13:36:35

How to parse date from excel to java?

When trying to parse an excel file and write it to an object, it throws an exception stating that

Cannot get a numeric value from a text cell
in the date field.

Question: how to correctly parse the date?

excel:
615b10a790fab703427611.png

code:
@Data
public class BaseModel {
    private Date dateTime;
    private int paymentId;
    private String paymentPurpose;
    private int sum;

}


@PostMapping("/import")
    public void mapReapExcelDatatoDB(@RequestParam("file") MultipartFile reapExcelDataFile) throws IOException {
        List<BaseModel> models = new ArrayList<>();
        XSSFWorkbook workbook = new XSSFWorkbook(reapExcelDataFile.getInputStream());
        XSSFSheet worksheet = workbook.getSheetAt(0);
        DataFormatter formatter = new DataFormatter();


        for(int i=1; i<worksheet.getPhysicalNumberOfRows() ;i++) {
            BaseModel baseModel = new BaseModel();

            XSSFRow row = worksheet.getRow(i);

            baseModel.setDateTime(row.getCell(0).getDateCellValue());
            baseModel.setPaymentId((int) row.getCell(1).getNumericCellValue());
            baseModel.setPaymentPurpose(row.getCell(2).getStringCellValue());
            baseModel.setSum((int) row.getCell(3).getNumericCellValue());
            models.add(baseModel);
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mystifier, 2021-10-04
@mystifier

There is such a piece from the processing of different types of excel fields

switch (sh.getRow(r).getCell(cell).getCellType()) {
      case HSSFCell.CELL_TYPE_NUMERIC:
        if (HSSFDateUtil.isCellDateFormatted(sh.getRow(r).getCell(cell))) {
          Date aDate = sh.getRow(r).getCell(cell).getDateCellValue();
          SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
          res = sdf.format(aDate);
        } else {
          sh.getRow(r).getCell(cell).setCellType(Cell.CELL_TYPE_STRING);
          res = sh.getRow(r).getCell(cell).getStringCellValue();
        }
        break;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question