使用 Apache POI 更改行的样式



我尝试更改行的背景颜色,或使用以下代码用不同的颜色突出显示它:

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();

我创建一个样式,将其设置为一行,然后将其写出到同一个文件中。执行代码时文件被修改,但背景颜色没有改变。

setRowStyle(CellStyle style)无法按预期工作。查看XSSFRow源代码,您将找不到对行中单元格的迭代或类似的东西。

/**
 * 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);
    }
}

据我所知,这更像是设置默认行样式。但是,即使您以后以这种方式设置行样式,在此行中创建的单元格也不会获得此样式。很可能您将不得不逐个单元格进行样式设置。

最新更新