使用单元格样式

我正在从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我得到1534 + E12。

我该如何解决?

问题在于单元格样式不仅控制单元格的颜色,还控制应用于其的格式。 所以,发生什么事是你要replace格式为#。#%的单元格样式,而是应用一个例如红色,但没有应用数字/date格式的规则。

单元格样式是工作簿的范围,所以你不应该为每个单元格创build一个,所以你应该使你的逻辑有点像:

 // 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); } 

你可以将它转换成一个string,如果你不需要做任何date处理,

 cell.setCellType(CELL_TYPE_STRING); 

无论如何,您可以通过从单元格获取date值到Java.Util.Date对象,然后保存它。bacl = k:

 Date date=cell.getDateCellValue(); //colour change cell.setValue(date); 

我现在没有时间来testing这个,但是让我知道它是否有效,如果没有的话,我会再看看。

你可以在这里获得更多的信息