简体   繁体   中英

POI - Handling data in HH:MM:SS.sss Format

I am working in a project where I have data in HH:MM:SS.sss format, I have to generate report in Excel/Spreadsheet. I am using POI to generate the excel file, but I am facing the following problems:

  1. If I set data in string format ie cell.setCellValue("02:45:6.7"); it is impossible to use Excel formulas such as average , sum , etc. Even if I format the cell in [h]:mm:ss.000;@ ie cs.setDataFormat(df.getFormat("[h]:mm:ss.000;@")) is does not works, as it is string.

    HSSFCellStyle cs = hssfworkbook.createCellStyle(); HSSFDataFormat df = hssfworkbook.createDataFormat(); cs.setDataFormat(df.getFormat("[h]:mm:ss.000;@"));

  2. Excel does not have any function(as per my knowledge) which takes data in hh:mm:ss.sss format, I tried using 'TIME(HH,MM,SS)' and formatting the cell to [h]:mm:ss.000;@ it does not shows value after decimal point replaces it with 000 ie TIME(02,45,6.7) is displayed as 02:45:6.000

  3. I tried making changes in POI source code, I tried the steps as per in this question https://stackoverflow.com/a/10306350/2513084 Still it does not work. The generated file says - some formulae or name of this file contains built-in functions which Kingsoft Spreadsheet does not support, and recalculation of these formulas or name may cause incorrect results. Microsoft Office was not able to open the file it gave the error File Error: data may have been lost.

I was not working with POI for a long time, but as far as I recall ... the dates are nothing else as numbers (milliseconds). Only the cell type is defined as a date/numeric cell.

The actual visual representation of the cell is then defined elsewhere.

Some old code of mine (probably not the latest POI version has this statement):

HSSFCell cell = newRow.createCell(column);

Date date = new Date(some_date_value); 
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(date);

You can set the cell style (display format) as:

cell.setCellStyle(style);

So I would dig into the style part ... and how to set it (Sorry have no working example of this part). Maybe it will work with your code ... as you are not setting the value as numeric but as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM