Java XSSFCellStyle setFillForegroundColor和setFillBackgroundColor不';行不通

Java XSSFCellStyle setFillForegroundColor和setFillBackgroundColor不';行不通,java,xssf,Java,Xssf,我尝试使用setFillForegroundColor和setFillBackgroundColor来更改excel文件的单元格颜色 然而,我失败了,我真的不知道问题出在哪里。我在谷歌上搜索了好几个小时,仍然找不到正确的颜色设置方法 以下是我编写的代码: import java.awt.Color; import java.io.File; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFCel

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

然而,我失败了,我真的不知道问题出在哪里。我在谷歌上搜索了好几个小时,仍然找不到正确的颜色设置方法

以下是我编写的代码:

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();
        }
    }
}
这是最终的结果

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


我使用的是来自

的poi-bin-3.12-20150511.zip。设置前景色后,您可能需要添加以下行:

style.setFillPattern(CellStyle.SOLID_FOREGROUND);
应为FillPatterType,因此应为:

style.setFillPattern(FillPatternType.SOLID_FOREGROUND)

它是否将单元格A1的值设置为“123”?对不起,我的代码应该是“no blue”而不是“123”。由于POI 3.x,正确答案如下: