Java – xssfcellstyle setfillforeroundcolor and setfillbackgroundcolor do not work

I try to use setfillforeroundcolor and setfillbackgroundcolor to change the cell color of Excel file

But I failed. I really don't know what the problem is I Google for hours and still can't find the right way to set the color

Here is the code I wrote:

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

This is the final result

How do I set the color of a cell to blue?

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

Solution

After setting the foreground color, you may need to add the following lines:

style.setFillPattern(CellStyle.soLID_FOREGROUND);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>