简体   繁体   English

Apache POI-允许使用时间字符串进行计算

[英]Apache POI - Allow calculation with time strings

I have an excel sheet which contains some time values. 我有一个Excel工作表,其中包含一些时间值。 These values are Durations formatted to Strings. 这些值是“持续时间”,格式为“字符串”。 When I try to do a sum on those values I get a 0 as result since Excel can't do sums on Strings. 当我尝试对这些值求和时,由于Excel无法对字符串求和,因此结果为0。 When I hit the enter button in the formula bar it does become a time so I the sum works. 当我按下公式栏中的Enter按钮时,它确实变成了一个时间,所以我的总和起作用了。 How do I change the value of the cell from a String to a time value? 如何将单元格的值从字符串更改为时间值? I already have the date format set up as [hh:mm] with a DateFormat 我已经使用DateFormat将日期格式设置为[hh:mm]

I start with an amount of time converted into seconds which I convert into a Duration 我先将时间转换为秒,然后将其转换为Duration

Duration clockedDuration = Duration.ofSeconds(clockedSeconds)

Then I format the Duration to a String using DurationFormatUtils 然后我使用DurationFormatUtils将Duration格式化为字符串

DurationFormatUtils.formatDuration(duration.toMillis(), "HH:mm", true)

Then I set the cell value to the String that was just made 然后,将单元格值设置为刚创建的String

c.setCellValue(clockedDuration)

I then set the CellStyle to one that has a DataFormat that's set up as [hh]:mm 然后,我将CellStyle设置为一种具有设置为[hh]:mmDataFormat

Lastly I make a sum of all the values in that particular column (B in this instance) 最后,我对该列中的所有值求和(在本例中为B)

c = r.createCell(i++)
c.setCellFormula("SUM(B2:B" + lastRow +")")
c.setCellType(Cell.CELL_TYPE_FORMULA)

This is the sheet before I hit the enter button on the first value in the row (09:52) 这是我点击该行第一个值上的回车按钮之前的工作表(09:52)

在此处输入图片说明

This is the sheet after I've hit the enter button in the formula bar 这是我在公式栏上按Enter键后的工作表

在此处输入图片说明

Just a hunch: you mentioned to actually use formulas, and if you are hitting enter on the sheet "the sum works". 只是预感:您提到实际使用公式,如果要单击,请在工作表上输入“和有效”。 Applying formulas is a two-liner, in addition to set the "value", you also need to format the cell type as being a formula: 应用公式是两方面的,除了设置“值”之外,您还需要将单元格类型设置为公式格式:

XSSFRow row = worksheet.getRow(rowIndex);
XSSFCell cell = row.getCell(cellIndex);
cell.setCellType(XSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula("sum(start:end)");

Edit: You also will want to make sure to use the XSSF-Classes 编辑:您还将要确保使用XSSF类

我通过将秒除以86400来获得十进制值,然后使用[hh]:mm作为数据格式来解决此问题。

c.setCellValue(clockedSeconds / 86400)  // 24(hours) * 60(minutes) * 60(seconds) = 86400

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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