我使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
874 次 |
| 最近记录: |