[英]Setting date format to excel cell with apache POI is not working
[英]APACHE POI setting cell style clears existing date format
我是 Java 编程的新手,这是我的第一篇文章,所以希望这是一个有效的问题。 我搜索了档案,但找不到合适的答案。
我的班级正在阅读和验证电子表格。 错误的单元格设置为红色背景样式,有效单元格设置为没有背景的样式。 这一切正常,直到遇到日期单元格。 setCellStyle 语句似乎正在清除日期格式。 谁能告诉我如何防止这种情况?
因此,当开始在 Excel 中查看单元格时,它会显示 25/08/20。
在我的程序中将样式更新为背景红色后,然后返回 Excel,单元格显示为红色,但其数值为 92345678.0000(我现在不记得确切的值)。
这是相关的代码:
XSSFCellStyle styleBad = wb.createCellStyle();
XSSFCellStyle styleGood = wb.createCellStyle();
styleGood.setFillPattern(FillPatternType.NO_FILL);
styleBad.setFillForegroundColor(IndexedColors.RED.getIndex());
styleBad.setFillPattern(FillPatternType.SOLID_FOREGROUND);
if (!validateCell(cell, tca[cx], cellValues)) {
cell.setCellStyle(styleBad);
errorMessage += ("Cell " + (cx + 1) + " " + cellValues.cellMessage + ". ");
wbValid = false;
}
else {
cell.setCellStyle(styleGood); Mucks up date formatting??
}
数字格式模式是单元格样式的一部分。 因此,当您设置新的单元格样式时,您还将数字格式模式设置为默认值。
您可以使用CellUtil
向现有单元格样式添加属性,而不是将其设置为新样式。 CellUtil.setCellStyleProperties
方法能够添加新的单元格样式属性,但保留单元格已经存在的单元格样式属性。
...
Map<String, Object> properties = new HashMap<String, Object>();
...
if (!validateCell(cell, tca[cx], cellValues)) {
properties = new HashMap<String, Object>();
properties.put(CellUtil.FILL_PATTERN, FillPatternType.SOLID_FOREGROUND);
properties.put(CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.RED.getIndex());
CellUtil.setCellStyleProperties(cell, properties);
errorMessage += ("Cell " + (cx + 1) + " " + cellValues.cellMessage + ". ");
wbValid = false;
}
else {
properties = new HashMap<String, Object>();
properties.put(CellUtil.FILL_PATTERN, FillPatternType.NO_FILL);
CellUtil.setCellStyleProperties(cell, properties);
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.