Setting Time in Excel using POI

后端 未结 3 1248
谎友^
谎友^ 2021-02-09 18:40

I am trying to create an Excel Work sheet using POI api in Java. In that Excel Work Sheet I want to have a cell with TIME alone. By setting this we can include the cell in summa

相关标签:
3条回答
  • 2021-02-09 18:56

    Dates and Times in Excel are normally stored as floating point numbers, as full and fractional days since 1900 or 1904. You can see this by typing 0.5 into an excel cell and formatting as a time - it'll show as 12:00:00, or set a value of 1.5 and it'll show as a date in 1900/1904 as a date, 12:00:00 as a time, or 36:00:00 if a time that allows >24 hours (it's a different format code)

    What you'll want to do is fire up a copy of Excel, type in the time value you want to have displayed, and work out the format string that makes it show up as you want it to. Then, make a note of that format code, and give that to POI as the data format for the cell. Now, use something like DateUtil in POI to build up your Date object, and set that to the cell as the value. With the right format string in, Excel will show only the time part and not the date

    0 讨论(0)
  • 2021-02-09 19:10

    I have used the following code to generate the time cell, in Excel using POI. And I am able to use the cell in

            XSSFRow row2 = sheet.createRow(25);
            XSSFCell cell1 = row2.createCell(4);
            XSSFCell cell2 = row2.createCell(5);
    
            CellStyle style = wb.createCellStyle();
            DataFormat df = wb.createDataFormat();
            style.setDataFormat(df.getFormat("[h]:mm:ss;@"));
    
            cell1.setCellFormula("TIME(0,15,00)"); // 00:15:00
            cell1.setCellType(Cell.CELL_TYPE_FORMULA);
            cell1.setCellStyle(style);
            evaluator.evaluateFormulaCell(cell1);
    
            cell2.setCellFormula("TIME(0,30,00)"); //00:30:00
            cell2.setCellType(Cell.CELL_TYPE_FORMULA);
            evaluator.evaluateFormulaCell(cell2);
            cell2.setCellStyle(style);
    
    0 讨论(0)
  • 2021-02-09 19:13

    You can use DateUtil.convertTime(String time) method where time is like "HH:MM" or "HH:MM:SS". This method will give you a double value which you can set as value in your cell (cell.setCellValue(double value)).

    But convertTime method doesn't work with hours > 23. If you need this opportunity, you can write your own convertTime method, somthing like this:

    double convertTime(long hours, long minutes, long seconds) {
       double totalSeconds = seconds + (minutes + (hours) * 60) * 60;
       return totalSeconds / (SECONDS_PER_DAY);
    }
    

    SECONDS_PER_DAY = 60 * 60 * 24. You can simply take it from DateUtil class.

    Remember, you must define your cell format properly that excel can put in hours more than 23.

    0 讨论(0)
提交回复
热议问题