2013-07-09 56 views
7

我正在使用Apache poi和XLSX文件。我使用xssf类来动态创建电子表格。 我想设置单元格样式在for循环中,但它似乎并没有工作......这里是我的代码:设置单元格样式不起作用

for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);i++,gc.add(GregorianCalendar.DATE, 1),righe++){ 
     Row r = foglio.createRow(righe); 

     if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){ 
      XSSFCellStyle cs1 = wb.createCellStyle(); 
      cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex()); 
      cs1.setFillPattern(CellStyle.SOLID_FOREGROUND); 
      XSSFFont f = wb.createFont(); 
      f.setBold(true); 
      f.setColor(IndexedColors.RED.getIndex()); 
      cs1.setFont(f); 
      Cell c1 = r.createCell(0); 
       c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno()); 
       c1.setCellStyle(cs1); 
      Cell c2 = r.createCell(1); 
       c2.setCellValue(i); 
       c2.setCellStyle(cs1); 
     }    
     r.createCell(0).setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno()); 
     r.createCell(1).setCellValue(i); 

...这我只是一个代码的一部分... 我不明白为什么不工作。似乎cellstyle被忽略或overwrited ....

任何线索?

回答

4

CellStyles是per-workbook,并且Excel强加给文件允许的数字有一个硬限制,因此您需要确保在循环外创建单元格样式。然后

您的代码看起来是这样的:

XSSFCellStyle cs1 = wb.createCellStyle(); 
cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex()); 
cs1.setFillPattern(CellStyle.SOLID_FOREGROUND); 

XSSFFont f = wb.createFont(); 
f.setBold(true); 
f.setColor(IndexedColors.RED.getIndex()); 
cs1.setFont(f); 

for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH) i++,gc.add(GregorianCalendar.DATE, 1),righe++){ 
    Row r = foglio.createRow(righe); 

    if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){ 
     Cell c1 = r.createCell(0); 
     c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno()); 
     c1.setCellStyle(cs1); 
     Cell c2 = r.createCell(1); 
     c2.setCellValue(i); 
     c2.setCellStyle(cs1); 
    } 
} 

如果您遇到与不看非常像您期望的,最好的选择是因为你希望它在Excel风格的单元格的造型问题,保存文件,将其读入POI,然后查看Excel编写的单元格样式。有时,Excel可以做一些奇怪的事情,需要一些习惯,所以请检查它做什么来解决你需要做的事情!

+0

我已经尝试了你的方法,但没有解决任何问题...我也致力于创建一个.xlsx模型文件,但是我正在生成一个基于用户在运行时定义的一些标准的100%动态电子表格... – Medioman92

+0

此外,如果我使用“IndexedColor”类来设置背景,它总是会产生黑色 – Medioman92

+1

在答案的底部查看我的建议 - 在excel中根据需要创建它,从POI读取它并制定出来什么选项需要设置,使样式看起来像你想 – Gagravarr

6

你可以使用下面的方法,也许这会解决你的问题。

public static void setCellColorAndFontColor(XSSFCell cell, IndexedColors FGcolor, IndexedColors FontColor){ 
    XSSFWorkbook wb = cell.getRow().getSheet().getWorkbook(); 
    CellStyle style = wb.createCellStyle(); 
    XSSFFont font = wb.createFont(); 
    font.setBold(true); 
    font.setColor(FontColor.getIndex()); 
    style.setFont(font); 
    style.setFillForegroundColor(FGcolor.getIndex()); 
    style.setFillPattern(CellStyle.SOLID_FOREGROUND); 
    cell.setCellStyle(style); 
} 

当你调用这个方法的方法应该是这样

setCellColorAndFontColor(cell, IndexedColors.BLACK, IndexedColors.WHITE); 

将创建利用薄片黑色细胞背景色大胆&白色字体文本颜色。

+3

尽管每个单元格都会创建一种样式,但您不应该这样做,因为您会很快用完 - 样式是工作簿范围! – Gagravarr

相关问题