java 使用 XSSFColor 设置 RGB 颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37011921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:06:06  来源:igfitidea点击:

Setting RGB Colors with XSSFColor

javaapache-poi

提问by Kurai Bankusu

I'm trying to set an RGB Color Value using XSSFColorsetFillForeground()method below

我正在尝试使用下面的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);

I'm passing the short value however my foreground is getting set to black no matter what the RGB value. I haven't yet discovered why this is - any ideas?

我正在传递短值,但是无论 RGB 值是多少,我的前景都设置为黑色。我还没有发现这是为什么 - 有什么想法吗?

回答by rgettman

The getIndexed()method in XSSFColorhas Javadocs that state that it's for backwards compatibility. Basically, XSSF has no pallette, so it's useless to set an index of color in a CellStyle.

中的getIndexed()方法XSSFColor有 Javadoc,说明它是为了向后兼容。基本上,XSSF 没有调色板,因此在CellStyle.

However, XSSF has its own method of setting the foreground color in a style -- using the colors directly. Use the overload of setFillBackgroundColorthat directly takes a XSSFColor. It only exists in XSSFCellStyle, not the interface CellStyle, so cast it as a XSSFCellStylefirst.

但是,XSSF 有自己的方法来设置样式中的前景色——直接使用颜色。使用那个的重载setFillBackgroundColor直接需要一个XSSFColor. 它只存在于 中XSSFCellStyle,不存在于interface 中CellStyle,因此将其作为XSSFCellStyle第一个。

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

回答by Rafael

You can check the example provided by the Apache Colors and Fills

您可以查看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);