Java XSSFCellStyle setFillForegroundColor 和 setFillBackgroundColor 不起作用

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

XSSFCellStyle setFillForegroundColor and setFillBackgroundColor doesn't work

javaxssf

提问by Brian

I tried to use setFillForegroundColor and setFillBackgroundColor to change the cell color of an excel file.

我尝试使用 setFillForegroundColor 和 setFillBackgroundColor 来更改 Excel 文件的单元格颜色。

However, I failed and I really didn't know what the problem was. I've googled for many hours and still couldn't find the right way to set the color.

但是,我失败了,我真的不知道问题出在哪里。我已经用谷歌搜索了很多小时,仍然找不到设置颜色的正确方法。

The following is the code I write:

下面是我写的代码:

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestColor {
    public static void main(String[] args) {
        File f = new File("test.xlsx");
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet();
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("no blue");

        // set the color of the cell
        XSSFCellStyle style = wb.createCellStyle();
        XSSFColor myColor = new XSSFColor(Color.BLUE);
        style.setFillForegroundColor(myColor);
        style.setFillBackgroundColor(myColor);
        cell.setCellStyle(style); // this command seems to fail

        try {
            FileOutputStream fos = new FileOutputStream(f);
            wb.write(fos);
            wb.close();
            fos.flush();
            fos.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

And this is the final result.

而这就是最终的结果。

enter image description here

在此处输入图片说明

How can I set the cell's color to blue?

如何将单元格的颜色设置为蓝色?

I'm using poi-bin-3.12-20150511.zip from https://poi.apache.org/download.html

我正在使用来自https://poi.apache.org/download.html 的poi-bin-3.12-20150511.zip

采纳答案by McNultyyy

You may need to add the following line after setting the foreground colour:

设置前景色后,您可能需要添加以下行:

style.setFillPattern(CellStyle.SOLID_FOREGROUND);

回答by Gwidion

SetFillPatternexpects FillPatterType, so rather this:

SetFillPattern需要 FillPatterType,所以更确切地说:

style.setFillPattern(FillPatternType.SOLID_FOREGROUND)