You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Apache POI在Excel单个单元格插入多段带样式的<p>标签内容

Apache POI实现同一单元格内不同字体分段显示

要实现把两段带不同字体的文本放到Excel同一个单元格并换行呈现,核心是利用Apache POI的**富文本字符串(RichTextString)**功能,给不同文本段单独设置字体样式,再结合单元格自动换行来实现段落效果。以下是完整的实现代码:

实现步骤与代码示例

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelRichTextExample {
    public static void main(String[] args) {
        // 创建工作簿和工作表
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("RichTextDemo");
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);

            // 开启单元格自动换行,实现段落换行效果
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            cell.setCellStyle(cellStyle);

            // 创建两种字体样式:Caveat和Arial
            Font caveatFont = workbook.createFont();
            caveatFont.setFontName("Caveat");
            caveatFont.setFontHeightInPoints((short)12);

            Font arialFont = workbook.createFont();
            arialFont.setFontName("Arial");
            arialFont.setFontHeightInPoints((short)12);

            // 构建富文本字符串,分段设置字体
            String caveatText = "This is Caveat";
            String arialText = "This is Arial text";
            String fullText = caveatText + "\n" + arialText;

            XSSFRichTextString richText = new XSSFRichTextString(fullText);
            // 给第一段文本应用Caveat字体
            richText.applyFont(0, caveatText.length(), caveatFont);
            // 给第二段文本应用Arial字体(跳过中间的换行符)
            richText.applyFont(caveatText.length() + 1, fullText.length(), arialFont);

            // 将富文本设置到单元格
            cell.setCellValue(richText);

            // 调整行高以适应换行后的内容
            row.setHeightInPoints(2 * sheet.getDefaultRowHeightInPoints());

            // 写入Excel文件
            try (FileOutputStream fos = new FileOutputStream("RichTextExample.xlsx")) {
                workbook.write(fos);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

关键说明

  • 自动换行:通过CellStyle.setWrapText(true)开启单元格自动换行,配合文本中的\n实现段落分隔,对应HTML中<p>标签的换行效果。
  • 富文本字体设置:XSSFRichTextString.applyFont(startIndex, endIndex, font)方法可精准给指定范围的文本应用字体样式,需注意索引计算(要跳过换行符的位置)。
  • 字体兼容性:确保运行环境或目标Excel打开环境中安装了Caveat字体,否则会被替换为系统默认字体。如果是从HTML标签解析,可先用Jsoup等工具提取每个<p>标签的文本和font-family属性,再动态创建字体并应用。

内容的提问来源于stack exchange,提问作者user2755407

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 08:52:40