【问题标题】:Change style of a row with Apache POI使用 Apache POI 更改行的样式
【发布时间】:2019-08-19 08:12:43
【问题描述】:

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

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

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

【问题讨论】:

  • 1.不要转发相同的问题。 2. 您的代码仍然无法编译。 3. 看看我在你上一个问题中所说的
  • @XtremeBaumer :我在我的代码中的这个方法中没有使用 createCell() 方法。变量src 包含一个文件路径,但这是我的全部代码。

标签: java apache-poi xls poi-hssf


【解决方案1】:

setRowStyle(CellStyle style) 无法正常工作。看看XSSFRow source code,你不会发现对行中单元格的迭代或类似的东西。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2013-03-22
    相关资源
    最近更新 更多