Java 为 HSSFCellStyle 设置前景色总是黑色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2803841/
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-08-13 13:00:41  来源:igfitidea点击:

Setting foreground color for HSSFCellStyle is always coming out black

javaapache-poipoi-hssf

提问by Ascalonian

I am using POI to create an Excel spreadsheet in Java. I have the following code used for creating a header row:

我正在使用 POI 在 Java 中创建 Excel 电子表格。我有以下代码用于创建标题行:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Report");

// some more code

HSSFRow row = sheet.createRow(0);

HSSFCell cell = row.createCell(cellNumber);
HSSFCellStyle cellStyle = wb.createCellStyle();

cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(HSSFColor.WHITE.index);

cellStyle.setFont(font);
cell.setCellStyle(cellStyle);

The issue I am having is that setting the fill background color on the cell always comes out black, no matter what color I pick. What am I doing wrong? If I don't use the "setFillPattern" line, no color shows up at all.

我遇到的问题是,无论我选择什么颜色,在单元格上设置填充背景颜色总是黑色。我究竟做错了什么?如果我不使用“setFillPattern”行,则根本不会显示任何颜色。

采纳答案by Ascalonian

I got this to work. I had to set the foreground color to make the background color work (??).

我得到了这个工作。我必须设置前景色以使背景色起作用(??)。

So I changed:

所以我改变了:

cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);

to:

到:

cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

and it worked!

它奏效了!

回答by dizzy

If you are setting the foreground color, use

如果要设置前景色,请使用

cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

If you are setting the background color, use

如果要设置背景颜色,请使用

style.setFillPattern(FillPatternType.THICK_BACKWARD_DIAG);

or

或者

style.setFillPattern(FillPatternType.THIN_BACKWARD_DIAG);

The foreground and background colors seem to 'stack' (red + blue = purple) if you set the foreground fill pattern before the background fill pattern, but not the other way round. There are several other fill patterns you can choose from. Note that the color will not be applied if you do not change the default fill pattern.

如果在背景填充图案之前设置前景填充图案,则前景和背景颜色似乎“堆叠”(红色 + 蓝色 = 紫色),但反之则不然。您可以选择其他几种填充图案。请注意,如果您不更改默认填充图案,则不会应用颜色。

CellStyle.SOLID_FOREGROUNDis deprecated in version 3.15+. Use FillPatternType.SOLID_FOREGROUNDinstead.

CellStyle.SOLID_FOREGROUND在 3.15+ 版本中已弃用。使用FillPatternType.SOLID_FOREGROUND来代替。