1 回答
TA贡献2036条经验 获得超8个赞
在您的代码部分之后:
...
String timeF = tf.substring(0, 5);
cellTimeF.setCellValue(timeF);
...
单元格内容将始终是字符串(文本)单元格内容。该内容的功能MIN和MAX不能使用。这些函数需要数字内容。在Excel日期和时间中也是数字内容仅格式化为日期时间。默认设置为 1 = 1 天 = 01/01/1900 00:00:00。1 小时 = 1/24,1 分钟 = 1/24/60,1 秒 = 1/24/60/60。
如果String timeF是格式为“HH:MM:SS”的字符串,则可以使用DateUtil.convertTime将此字符串转换为Excel有价值的时间。
完整示例,显示什么不起作用以及什么起作用:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
public class ExcelCalculateTimeValues {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle styletime = workbook.createCellStyle();
styletime.setDataFormat(createHelper.createDataFormat().getFormat("hh:mm:ss"));
Sheet sheet = workbook.createSheet();
sheet.createRow(0).createCell(0).setCellValue("Start");
sheet.getRow(0).createCell(1).setCellValue("End");
sheet.getRow(0).createCell(3).setCellValue("Start");
sheet.getRow(0).createCell(4).setCellValue("End");
String[][] tableData = new String[][]{
{"12:34:00", "22:45:00"},
{"23:45:00", "01:34:00"},
{"08:01:00", "13:23:00"}
};
int r = 1;
for (String[] rowData : tableData) {
Row row = sheet.createRow(r++);
int c = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(c);
cell.setCellValue(cellData); //this sets string cell data
cell.setCellStyle(styletime);
cell = row.createCell(3 + c++);
cell.setCellValue(DateUtil.convertTime(cellData)); //this sets datetime cell data
cell.setCellStyle(styletime);
}
}
sheet.createRow(r).createCell(0).setCellFormula("MIN(A2:A4)"); //cannot work because of string values in A2:A4
sheet.getRow(r).createCell(1).setCellFormula("MIN(B2:B4)"); //cannot work because of string values in B2:B4
sheet.getRow(r).createCell(3).setCellFormula("MIN(D2:D4)"); //will work
sheet.getRow(r).createCell(4).setCellFormula("MIN(E2:E4)"); //will work
workbook.setForceFormulaRecalculation(true);
workbook.write(new FileOutputStream("ExcelCalculateTimeValues.xlsx"));
workbook.close();
}
}
所以用你的代码:
...
cellTimeF.setCellValue(DateUtil.convertTime(timeF));
...
和
...
cellTimeT.setCellValue(DateUtil.convertTime(timeT));
...
应该管用。
添加回答
举报