Search code examples
javaexcelheaderapache-poi

How to set font color for Excel header text using JAVA


I am trying to set a font color of header text of Excel sheet using Apache POI. As attached screenshot. My code is,

    Footer footer = sheet.getFooter();
    footer.setLeft(HSSFHeader.font(footerFontName, "Regular") +
                             HSSFHeader.fontSize((short) footerFontSize) +
                             footerInfo);

How to set header text in red color using JAVA Code.

enter image description here


Solution

  • Excel provides special codes to format headers and footers. See Formatting and VBA codes for headers and footers. The mentioned texts &... have special meaning in headers and footers. They are not printed but used to determine the formats. So simplest way is using those codes. Note &color needs to be &Kcolor where coloris a hexadecimal value.

    Example:

    import java.io.*;
    
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.*;
    import org.apache.poi.hssf.usermodel.*;
    
    public class CreateExcelHeaderText {
    
     public static void main(String[] args) throws Exception {
    
      Workbook workbook = new XSSFWorkbook(); String filePath = "./CreateExcelHeaderText.xlsx";
      //Workbook workbook = new HSSFWorkbook(); String filePath = "./CreateExcelHeaderText.xls";
    
      Sheet sheet = workbook.createSheet();
    
      Header header = sheet.getHeader();
      header.setCenter("&C&KFF0000&24CENTER HEADER"); // &C = text centered; &KFF0000 = font color red; &24 = font size 24pt
    
      FileOutputStream out = new FileOutputStream(filePath);
      workbook.write(out);
      out.close();
      workbook.close();
    
     }
    }
    

    This leads to a centered header in red font color and font size 24pt.

    Some of those codes also can be set using HeaderFooter. But &K... is not supported there until now.