简体   繁体   中英

Colored Header cells with java Apache POI

I want to have my header row in different colors. Until now I just have different colors for the Font, because the background color does not work like I wish. My output File should be in the xls-format.

   import org.apache.poi.xssf.usermodel.XSSFCellStyle;
   import org.apache.poi.xssf.usermodel.XSSFWorkbook;
   ...


    String[] mylmcol = {"EmplNo", "LMSurname", "LMFirstname"};
    String[] myusercol = {"UserID", "USRSurname", "USRFirstname"};
    String[] rolecol = {"Group", "Role"};
    String[] ackcol = {"ACKValue"};

    XSSFWorkbook workbook_cbk_output = new XSSFWorkbook();
    Sheet sheet_cbk_output = workbook_cbk_output.createSheet("UserList");

    Font LMheaderFont = workbook_cbk_output.createFont();
    LMheaderFont.setFontHeightInPoints((short) 12);
    LMheaderFont.setColor(IndexedColors.SEA_GREEN.getIndex());

    ...

    XSSFCellStyle headerCellStyleACK = workbook_cbk_output.createCellStyle();
    headerCellStyleACK.setFont(ACKheaderFont);
    //DOES NOT WORK:
    headerCellStyleACK.setFillBackgroundColor(HSSFColor.AQUA.index);
    headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    Row headerRow_cbk = sheet_cbk_output.createRow(0);

    for (int i = 0; i < mylmcol.length; i++) {
        Cell cell = headerRow_cbk.createCell(i);
        cell.setCellValue(mylmcol[i]);
        cell.setCellStyle(headerCellStyleLM);
    }
    ...
    FileOutputStream OUTFILE = new FileOutputStream("Myoutput.xls");
    workbook_cbk_output.write(OUTFILE);
    OUTFILE.close();

I tried the commands setFillBackgroundColor but this is igno. Is there another solution for coloring the background?

You may use the XSSFColor instead of HSSFColor , if you use XSSF worksheet/CellStyle. For me it works with:

XSSFCellStyle headingStyle = workbook.createCellStyle();
headingStyle.setFillForegroundColor( new XSSFColor( new java.awt.Color( 207, 207, 207 ) ) );
headingStyle.setFillPattern( CellStyle.SOLID_FOREGROUND );

and apply it to the cells/rows:

Row rowHeadingStyle = styleSheet.createRow( 0 );
rowHeadingStyle.setRowStyle( headingStyle );

This is setting the background color to the desired value!

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