0
votes

I have to open an existing Excel and set some values or change the background/foreground color at that cells.

This excel is about the worked days in a company, so I have an Excel already styled. I have to change the foreground at some cells because, as you can imagine, in some days we don't work.

So, for every day ( that corresponds to a cell ), if it is not "enabled" it has to become yellow.

My code is :

    for(int i=0;i<listDays.size();i++) {

            int indiceColonna = 6+i;

            /* Setto la cella GIALLA relativa alla desc corta giorno */
            if(!listDays.get(i).isEnabled()) {
                CellStyle cellaGialla = foglio.getRow(5).getCell(indiceColonna).getCellStyle();
                cellaGialla.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
                cellaGialla.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                foglio.getRow(5).getCell(indiceColonna).setCellStyle(cellaGialla);

            /* Colonne gialle : da G8 a G18 - a scendere */
                for (int y = 0; y < 11; y++) {
                    Cell cella = foglio.getRow(7 + y).getCell(6 + i);
                    CellStyle cella2Gialla = cella.getCellStyle();
                    cella2Gialla.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
                    cella2Gialla.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    cella.setCellStyle(cella2Gialla);
                }
            }

        }

I want to take the actual CellStyle of the cell and change only the foreground color. This code works partially because is setting the foreground color at other columns too : wrong columns

How can I avoid this error? I'm using Apache POI 3.16, but I tried with some older versions.

Thank you!

1
Create a new cell style, style that and apply it? Cell Styles are Workbook scoped in ExcelGagravarr

1 Answers

1
votes

I was also facing similar issue and found the solution to be creating a new style for the workbook as mentioned by Gagravarr. Just change your code as below.

CellStyle cella2Gialla = WorkbookObject.createCellStyle();