java – XSSFCellStyle setFillForegroundColor和setFillBackgroundColor不起作用

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

但是,我失败了,我真的不知道问题是什么.我用Google搜索了好几个小时,仍然无法找到正确的方法来设置颜色.

以下是我写的代码

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();
        }
    }
}

这是最终的结果.

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

我从https://poi.apache.org/download.html开始使用poi-bin-3.12-20150511.zip

解决方法

设置前景色后,您可能需要添加以下行:
style.setFillPattern(CellStyle.soLID_FOREGROUND);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...