简体   繁体   中英

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.

在此处输入图像描述

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 color is 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.

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