java - 使用 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);
}
}
据我所知,这更像是设置默认行样式。但是,即使您以这种方式设置行样式,之后在该行中创建的单元格也不会获得这种样式。很可能您将不得不逐个单元格地进行样式设置。
推荐阅读
- mathematical-optimization - 优化 min{x/(x+1)}
- django - 如何从 Django REST 框架(JWT 令牌)获取真实密码。对于用户列表视图
- flutter - NoSuchMethodError : 在 null 上调用了 setter 'text='。接收方:null 尝试调用:text="2020-12-10 00:00:00.000"
- xslt - XSLT 中不同 Xpath 之间的分组
- java - 如何将巨大的 id 列表(例如)传递给 apache spark 自定义数据源
- javascript - 使用 webpack 4.41 和 workbox 6 生成 ServiceWorker
- reactjs - React-Intl 同时使用多个语言环境
- flutter - StreamBuilder 快照 ConnectionState.done 不起作用
- python - 导航栏中的 Django 动态菜单
- javascript - PayPal 智能按钮交易显示错误