sharky
sharky

Reputation: 306

How to set color on blank cell

I need to set color for the one whole row but the problem is some of my cells are blank cell, not containing any data,

        XSSFRow row2 = sheet.getRow(1);

        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);

        for (int i = 0; i < row1.getLastCellNum() + 1; i++) {// For each cell in the row
            row2.getCell(i).setCellStyle(style);// Set the style
        }

I got error like this:

java.lang.NullPointerException

I believe this error come from the blank cell because when I try to set color on cell that contain data for example:

row2.getCell(4).setCellStyle(style);

the particular cell is in color accordingly.

Can we actually put color on a blank cell?

Upvotes: 1

Views: 337

Answers (1)

GauravRai1512
GauravRai1512

Reputation: 844

You should try below approach. Here i have given you logic as i don't have exactly the dependency please follow below approach First check if row2.getCell is not null then set otherwise create cell and then set.

 XSSFRow row2 = sheet.getRow(1);

            CellStyle style = wb.createCellStyle();
            style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);

            for (int i = 0; i < row2.getLastCellNum(); i++) {// For each cell in the row
                if( row2.getCell(i)!=null){
                row2.getCell(i).setCellStyle(style);// Set the style
                }else{
                    Cell cell=row2.createCell(i);
                    cell.setCellStyle(style);
                }
            }

Upvotes: 1

Related Questions