2014-03-29 81 views
2

我正在从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

单元格样式包括格式化规则,所以你需要保存这些呢! – Gagravarr

+0

你能举个例子吗? – Skizzo

回答

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

你既可以把它转换为字符串,如果你不需要做任何的数据处理就可以了以后像这样:

cell.setCellType(CELL_TYPE_STRING); 

therwise您可以通过获取从日期值做细胞进入Java.Util.Date对象,然后将其保存BACL = K:

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

我没有时间来测试这个权利,但现在让我知道,如果它的工作原理,如果没有,我会看起来更进去。

你可以得到更多的信息here

相关问题