首页 > 解决方案 > 带有 java Apache POI 的彩色标题单元格

问题描述

我想让我的标题行有不同的颜色。到目前为止,我只是为字体设置了不同的颜色,因为背景颜色不像我希望的那样工作。我的输出文件应该是 xls 格式。

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

我尝试了命令setFillBackgroundColor,但这是忽略。是否有另一种为背景着色的解决方案?

标签: javaapache-poi

解决方案


如果您使用 XSSF 工作表/CellStyle,则可以使用XSSFColor而不是。HSSFColor对我来说,它适用于:

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

并将其应用于单元格/行:

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

这是将背景颜色设置为所需的值!


推荐阅读