使用XSSFColor设置RGB颜色

8
我正在尝试使用下面的XSSFColorsetFillForeground()方法设置RGB颜色值。
XSSFWorkbook workbook= new XSSFWorkbook();
CellStyle style = workbook.createCellStyle();
Style.cloneStyleFrom(headerStyle);
Style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
XSSFColor color = new XSSFColor(new java.awt.Color(215,228,188)); //accepts a short value
style.setFillForegroundColor(color .getIndexed());

Sheet sheet = workbook.createSheet(sheetName);
Row headerRow = sheet.createRow(0);

Cell cell = headerRow.createCell(i);
cell.setCellStyle(style);

我传递了short值,但无论RGB值如何,我的前景色都被设置为黑色。我还未发现原因 - 有什么想法吗?
2个回答

14

XSSFColor中的getIndexed()方法的Javadocs说明它是为了向后兼容而存在。基本上,XSSF没有调色板,因此在CellStyle中设置颜色的索引是无用的。

但是,XSSF有自己的一种方法来设置样式中的前景色 - 直接使用颜色。使用直接接受XSSFColor参数的setFillBackgroundColor的重载方法。该方法仅存在于XSSFCellStyle中,而不是CellStyle接口,因此首先需要将其转换为XSSFCellStyle

((XSSFCellStyle) style).setFillForegroundColor(color);

1
这个运行得非常好。非常感谢你的帮助和解释。 - Clay Banks
唯一在NPOI中有效的解决方案...谢谢您先生 - Cabuxa.Mapache

2
你可以查看Apache Colors and Fills提供的示例。
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");
XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128), new DefaultIndexedColorMap()));
style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接