Home » excel » java – Apache POI write time greater than 24

java – Apache POI write time greater than 24

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to write a excel file. In this file there are some column where I put the time values like “11:21″. In the last row of this column, I want to add these time values and show the total like”123:23”. For this I am using the following code:

HSSFCellStyle cellStyle = wb.createCellStyle();
                    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm"));
                    c.setCellValue(DateUtil.convertTime("49:12"));
                    c.setCellStyle(cellStyle);

But It is giving me the following error:
java.lang.IllegalArgumentException: Bad time format ’49:12′ expected ‘HH:MM’ or ‘HH:MM:SS’ – hour value (49) is outside the allowable range(0..23)

Please help me.

How to&Answers:

This approach worked for me:
1. Set a custom data format [h]:mm
2. Get a java.util.Date object for your time using a SimpleDateFormat
3. Excel’s epoch is 1900, so set the year in your Date object to 1900 using Calendar
4. Set cell value as your Date object after deducting 1 day

CreationHelper createHelper = wb.getCreationHelper();

CellStyle hhmmStyle = wb.createCellStyle();
hhmmStyle.setDataFormat(createHelper.createDataFormat().getFormat("[h]:mm"));

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

xlsCell.setCellStyle(hhmmStyle);

Date time = sdf.parse("49:00");
Calendar cal = Calendar.getInstance();
cal.setTime(time);
cal.set(Calendar.YEAR, 1900);

xlsCell.setCellValue(DateUtil.getExcelDate(cal.getTime())-1.0);

Answer:

Try to use SimpleDateFormat,

    SimpleDateFormat _24HourFormat = new SimpleDateFormat("HH:mm");
    SimpleDateFormat _12HourFormat = new SimpleDateFormat("hh:mm");

For example

SimpleDateFormat _24HourFormat = new SimpleDateFormat("HH:mm");
Date date = _24HourFormat.parse("49:12");
cell.setCellValue(date);

Answer:

You could add an apostrophe at the first position of your data in order to set the value as String, no need to set the value as a Date.

c.setCellValue("'49:12");