简体   繁体   中英

How to set background color for merged cells in Apache POI

在此处输入图片说明

I use the following code to set background color for cells:

XSSFCellStyle cellStyle = (XSSFCellStyle) excelStyle.getCellStyle();
cellStyle.setFillForegroundColor(new XSSFColor(java.awt.Color.decode("#FFFF99")));
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

But it is not working for cells which are merged, it always becomes black no matter of what I try to set. It is working only if I set a predefined color like:

cellStyle.setFillForegroundColor(IndexedColors.CORAL.index);

The color is defined by user so I can't use IndexedColors . Also, I can't create a custom palette color (as explained here ) because my workbook is of type SXSSFWorkbook , not HSSFWorkbook .

How to set background color for merged cells?

I have tried below steps and working for me.

  1. Create a sheet
  2. Create a row
  3. Create style with custom colors using RGB values
  4. Loop for creating cell > create cell and add value to cells 0 which will appear for subsequent merged cells, apply style to every cell,
  5. Finally merge cells > lets say you want to merge cell 0 to cell 3 of row 0 use sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));

After lot of debugging I found issue which was causing the merged cell to be always black was below line.

CellUtil.setAlignment(sheetSummary.getRow(0).getCell(4), HorizontalAlignment.CENTER_SELECTION);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM