我使用apache poi将CSV文件重写为Excel,对于像HH:mm:ss这样的任何字符串,我都需要将其转换为适当的Excel数据类型,以便用户可以在该列上应用sum()函数。我尝试了不同的数据类型,但是当我打开excel文件时,我无法对该列求和,总和始终显示为“ 0:00:00”,即使单击excel中的该列也显示为“时间”数据类型,
这是我的代码:
CreationHelper creationHelper = workbook.getCreationHelper();
HSSFCellStyle timeStyle = workbook.createCellStyle();
timeStyle.setDataFormat(creationHelper.createDataFormat().getFormat("h:mm:ss"));
cell.setCellValue(column);
if (isTime(column)) {
cell.setCellStyle(timeStyle);
}
private boolean isTime(String value) {
try {
dtf.parseDateTime(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
答案 0 :(得分:6)
如果代码中的对象column
是String
,则单元格的内容将始终是cell.setCellValue(column)
之后的字符串(文本)单元格内容。此内容SUM
无法使用。这些功能需要数字内容。在Excel
中,日期和时间也是仅格式化为日期时间的数字内容。默认设置为1 = 1天= 01/01/1900 00:00:00。 1小时= 1 / 24,1分钟= 1/24 / 60,1秒= 1/24/60/60。
如果column
是格式为“ 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.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
public class ExcelCalculateTimeValues {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
//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("Time sting");
sheet.getRow(0).createCell(1).setCellValue("Time");
String[][] tableData = new String[][]{
{"12:34:00", "22:45:00"},
{"23:45:05", "01:34:40"},
{"08:01:00", "13:23:00"},
{"15:41:12", "23:23:22"}
};
int r = 1;
for (String[] rowData : tableData) {
Row row = sheet.createRow(r++);
int c = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(c);
if (c == 0 ) {
cell.setCellValue(cellData); //this sets string cell data
} else if (c == 1) {
cell.setCellValue(DateUtil.convertTime(cellData)); //this sets datetime cell data
}
cell.setCellStyle(styletime);
c++;
}
}
sheet.createRow(r).createCell(0).setCellFormula("SUM(A2:A"+r+")"); //cannot work because of string values in A2:A4
sheet.getRow(r).createCell(1).setCellFormula("SUM(B2:B"+r+")"); //will work
workbook.setForceFormulaRecalculation(true);
if (workbook instanceof HSSFWorkbook) {
workbook.write(new FileOutputStream("ExcelCalculateTimeValues.xls"));
} else if (workbook instanceof XSSFWorkbook) {
workbook.write(new FileOutputStream("ExcelCalculateTimeValues.xlsx"));
}
workbook.close();
}
}