0

I am using Apache Poi for writing of data Into the Excel Sheet. I have a requirement to merge cells and set background for the merged Cells. I have a code for merged cell but I don't know how to set background or foreground for the Cell.

// This code is the I used for merging cells and setting border for the cells

CellRangeAddress cellRangeAddress = new CellRangeAddress(rowNum,rowNum,colNum,colNum);

sheet.addMergedRegion(cellRangeAddress);

RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, mergedCell, sheet, workBook);

RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, mergedCell,sheet, workBook);

RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, mergedCell, sheet, workBook);

RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, mergedCell,sheet, workBook);

I want to have background for the merged cells . Please help me with a code for setting background or foreground for the merged cells.

El cucuy
  • 85
  • 9
  • 2
    See https://stackoverflow.com/questions/50712340/apply-fill-colors-and-borders-to-excel-range-using-apache-poi/50762030#50762030 for an example for creating a complex Excel table having merged cells and different background colors set. – Axel Richter Jan 23 '19 at 06:27
  • Thanks you Axel Richter for the reply. I have checked the Link that you have provided but i didn't find `CellUtil.setCellStyleProperty(cell,properties)` Method .I guess it might may be jar file problem I am using 3.9 poi jar do I need to Update. – El cucuy Jan 23 '19 at 10:54
  • 1
    I have not used `CellUtil.setCellStyleProperty` but `CellUtil.setCellStyleProperties`. But you are correct, `apache poi 3.9` does not have that method, it has `setCellStyleProperty(Cell cell, Workbook workbook, String propertyName, Object propertyValue)` only. But `apache poi 3.9` is more than 6 years old now. That are aeons for such a project as `apache poi`. I recommend always using the latest stable version which is `apache poi 4.0.1` now. – Axel Richter Jan 23 '19 at 11:24
  • [link](https://stackoverflow.com/questions/54422443/merging-cells-vertically-and-inserting-data-into-the-cell) Done Axel – El cucuy Jan 29 '19 at 13:43

1 Answers1

1

Try below steps. Let me know if you have any question.

Create CellStyle object from workbook i.e workbook.createCellStyle set CellStyle properties like setAlignment,font,setFillForegroundColor,setFillPattern

and then pass the object to cell.setCellStyle

Imran.Khan
  • 186
  • 2
  • 7