java - 使用 Apache POI 更改行的样式

标签 java apache-poi xls poi-hssf

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

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

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

关于java - 使用 Apache POI 更改行的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55399599/

相关文章:

java - 运行在不同机器上的Kafka消费者组可以接收到唯一的消息吗?

java - 尝试理解 java SimpleTimeZone 规则

java - 如何使用 Jmeter 从 CSV 数据集读取数据时转义逗号?

java - 如何处理excel文件java中的空白单元格

java - 兴趣点 : wrong number of cell per row form method getPhysicalNumberOfCells

iOS:读取 XLS

java - 有没有办法为方法概述静态变量?

java - Java 中的 PDF 到 Excel

ruby-on-rails - Rspec respond_to xls

iphone - 在 iOS 上创建 Excel XLS 文件