Change style of a row with Apache POI

2.9k views Asked by At

I try to change background color of a row, or highlight it with a different color with use of following code:

FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
r = sheet.getRow(5);

CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
r.setRowStyle(style);

FileOutputStream fileOut = new FileOutputStream(excelFileName);
wb.write(fileOut);
wb.close();
fileOut.flush();
fileOut.close();

I create a style, set it to a row and after that I write it out to same file. File is modified when I execute code, but background color isn't changed.

1

There are 1 answers

0
Martin On BEST ANSWER

setRowStyle(CellStyle style) doesn't work as you would expect. Taking a look at the XSSFRow source code you will not find an iteration over the cells in the row or something similar.

/**
 * Applies a whole-row cell styling to the row.
 * If the value is null then the style information is removed,
 *  causing the cell to used the default workbook style.
 */
@Override
public void setRowStyle(CellStyle style) {
    if(style == null) {
       if(_row.isSetS()) {
          _row.unsetS();
          _row.unsetCustomFormat();
       }
    } else {
        StylesTable styleSource = getSheet().getWorkbook().getStylesSource();

        XSSFCellStyle xStyle = (XSSFCellStyle)style;
        xStyle.verifyBelongsToStylesSource(styleSource);
        long idx = styleSource.putStyle(xStyle);
        _row.setS(idx);
        _row.setCustomFormat(true);
    }
}

To my knowledge it is more like setting a default row style. But even when you set a row style this way afterwards created cells in this row won't get this style. Most probably you will have to do the styling cell by cell.