2014-03-06 124 views
0

我正在使用POI庫來處理Excel文件,我想更改特定單元格的ForGroundColor。由於我對IndexedColors列表不滿意,我想通過替換已存在的列表(我的情況爲HSSFColor.BLUE)來創建自己的列表,問題是 - 它僅保存上次迭代的顏色(所有單元格都相同顏色)。在Excel中動態更改單元格顏色

代碼(convData - 兩個模糊的雙陣列,標準化爲255):

 HSSFPalette hssfPalette = excelFile.getCustomPalette(); 
     CellStyle cellStyle = excelFile.createCellStyle(); 
     hssfPalette = excelFile.getCustomPalette(); 
     cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); 

     for (int i=0; i<convData.length; i++) { 
      Row row = excelSheet.createRow(i); 
      for (int j=0; j<convData[i].length; j++) { 
       Cell cell = row.createCell(j); 

       hssfPalette.setColorAtIndex(HSSFColor.BLUE.index, convData[i][j].byteValue(), convData[i][j].byteValue(), convData[i][j].byteValue()); 
       cellStyle.setFillForegroundColor(hssfPalette.getColor(HSSFColor.BLUE.index).getIndex()); 
       cell.setCellStyle(cellStyle); 
      } 
     } 

回答

2

你的問題是,你要創建一個單獨的單元格樣式,將其分配給了一堆細胞,然後改變它藍色部分通過。因爲單元格樣式是全局的,所以藍色適用於所有內容

而是,您需要移動循環外部的「重新定義藍色」,或創建新的單元格樣式+爲它們應用顏色,細胞。但是,顏色和單元格樣式的數量有限制,因此如果您有多個單元需要相同的顏色,請確保重新使用它們。