首页 > 解决方案 > 使用 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();

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

标签: javaapache-poixlspoi-hssf

解决方案


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

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


推荐阅读