简体   繁体   中英

java, unable to color cells with proper color, apache poi

I want to color 3 different sets of columns with 3 different colors, and this method is used to add the colors:

public static void addCellStyles(CellStyle stylex, CellStyle styley, CellStyle stylez){

    stylex.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.getIndex());
    stylex.setFillPattern(CellStyle.SOLID_FOREGROUND);
    stylex.setAlignment(CellStyle.ALIGN_CENTER);
    stylex.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    styley.setFillBackgroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
    styley.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styley.setAlignment(CellStyle.ALIGN_CENTER);
    styley.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    stylez.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
    stylez.setFillPattern(CellStyle.SOLID_FOREGROUND);
    stylez.setAlignment(CellStyle.ALIGN_CENTER);
    stylez.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
}

i'm assigning the CellStyles to the respective cells in the main function for some reason the cells are being colored black, and i cant seem to find any problem can anyone help me

Ironically the background-color is the foreground-color in POI/Excel.

Try it like this:

XSSFCellStyle style1 = workbook.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style1);

or in your case simply:

stylex.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
stylex.setFillPattern(CellStyle.SOLID_FOREGROUND);

and don't forget to assign the style to the cells. If you just take the initial style from three different cells, it will probably point to the same style object in the workbook. If you want a new style you have to create it in the workbook and assign it to the cell (see my example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM