我正在从excel文件中处理导入模块。我必须阅读并检查此文件,如果出现问题,我必须为颜色的相应单元着色。然后我实现了以下方法
public void fillCell(Workbook wb, Row row, int errorColumn){
Cell cell = row.getCell(j);
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor((short) 10);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cell.setCellStyle(cs);
}
但我注意到这种方法改变了细胞的数据格式。例如,如果我用数据值29/03/2014着色一个单元格,我得到彩色单元格,但它的值现在是39536,数值1534000001629也是如此,在这种情况下,我得到彩色单元格但是如果我尝试将值从1534000001629更改为1534000001630我得到1,534 + E12。
我该如何解决?
答案 0 :(得分:1)
问题是细胞样式不仅控制细胞的颜色,它们还控制应用于它的格式。所以,正在发生的事情是,您正在替换格式为#。#%的单元格样式,而是应用一个例如红色但没有应用数字/日期格式规则的单元格样式。
单元格样式是工作簿范围,因此您不应该为每个单元格创建一个,因此您应该使您的逻辑有点像:
// Lookup from number format to the coloured version
Map<String,CellStyle> styles = new Hashmap<String,CellStyle>();
// Method to make the cell a different colour
public void fillCell(Workbook wb, Row row, int errorColumn){
Cell cell = row.getCell(j);
// Try to find a coloured one for this data formatting
String formatStr = cell.getCellStyle().getDataFormatString();
CellStyle cs = styles.get(formatStr);
if (cs == null) {
// Need to create a new coloured one
cs = wb.createCellStyle();
cs.setFillForegroundColor((short) 10);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cs.setDataFormat(
wb.getCreationHelper().createDataFormat().getFormat(formatStr));
// Save this for later
styles.put(formatStr, cs);
}
// Apply the coloured form, with the format string
cell.setCellStyle(cs);
}
答案 1 :(得分:0)
如果您以后不需要对其进行任何日期处理,则可以将其转换为字符串:
cell.setCellType(CELL_TYPE_STRING);
你可以通过从单元格中获取日期值到Java.Util.Date对象然后保存它来实现它bacl = k:
Date date=cell.getDateCellValue();
//colour change
cell.setValue(date);
我现在没有时间对此进行测试,但请告诉我它是否有效,如果没有,我会更多地了解它。
您可以获得更多信息here