【问题标题】:Change color of specific text while generating Excel header生成 Excel 标题时更改特定文本的颜色
【发布时间】:2019-09-03 09:20:23
【问题描述】:

我正在使用 apache-poi 在基于 spring 的应用程序中生成 Excel。在填充 excel 的标题时,我希望给定句子的特定单词以不同的颜色显示。 例如-假设我希望我的标题具有值Address (*"MANDATORY) 并具有以下给定颜色。 Address - 黑色 *"MANDATORY - 红色 我通过了一种更改 apache-poi 提供的 fontColor 的方法,但这正在更改整个单元格值的字体颜色,但我想要不同颜色的特定文本。 如何解决上述问题?

【问题讨论】:

标签: java excel apache-poi


【解决方案1】:

为了满足您的要求,单元格必须包含富文本字符串内容。这可以使用Cell.setCellValue(RichTextString value)RichTextString 可以按照Busy Developers' Guide to HSSF and XSSF Features 中的描述创建。

让我们举个例子,它提供了一个方法createRichTextString(Workbook workbook, String[] textParts, Font[] fonts),它使用一个字体数组为一个文本部分数组创建一个RichTextString

import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

class CreateExcelRichText {

 static RichTextString createRichTextString(Workbook workbook, String[] textParts, Font[] fonts) {
  CreationHelper creationHelper = workbook.getCreationHelper();
  RichTextString richTextString = creationHelper.createRichTextString(String.join("", textParts));
  int start = 0;
  int end = 0;
  for (int tp = 0; tp < textParts.length; tp ++) {
   Font font = null;
   if (tp < fonts.length) font = fonts[tp];
   end += textParts[tp].length();
   if (font != null) richTextString.applyFont(start, end, font);
   start += textParts[tp].length();
  }
  return richTextString;
 }

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook(); 
  //Workbook workbook = new HSSFWorkbook();

  String fileName = (workbook instanceof XSSFWorkbook)?"Excel.xlsx":"Excel.xls";

  Font font = workbook.createFont(); // default font

  Font fontRed = workbook.createFont();
  fontRed.setColor(Font.COLOR_RED);

  String[] textParts = new String[]{"Address (", "*\"MANDATORY", ")"};
  Font[] fonts = new Font[]{font, fontRed, font};

  RichTextString richTextString = createRichTextString(workbook, textParts, fonts);

  Sheet sheet = workbook.createSheet();
  sheet.createRow(0).createCell(0).setCellValue(richTextString);

  FileOutputStream out = new FileOutputStream(fileName);
  workbook.write(out);
  out.close();
  workbook.close();
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2021-09-09
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多