POI 富文本RichTextString

本文介绍如何使用Apache POI库在Excel中创建富文本字符串,包括HSSFRichTextString和XSSFRichTextString的应用方法,以及如何设置不同字体样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 富文本RichTextString概述

富文本unicode字符串可以将字体Font应用于字符串的任何部分:

applyFont(int startIndex, int endIndex, Font font)
applyFont(int startIndex, int endIndex, short fontIndex)

这里写图片描述

2. HSSFRichTextString

创建HSSFRichTextString单元格的方式很重要,有时,创 建太多的HSSFRichTextString单元格会导致Excel 2003和 更低版本在更改单元格的颜色,然后保存Excel文件时崩溃

第一种:
HSSFCell hssfCell = row.createCell(idx);
RichTextString str = new HSSFRichTextString("富文本");
str.applyFont(0, 1, font1);
str.applyFont(1, 3, font2);
hssfCell.setCellValue(str);
第二种:
// 创建单元格样式style, 并为其分配第一个字体font1
CellStyle style = workbook.createCellStyle();
style.setFont(font1);
Cell cell = row.createCell(idx);
cell.setCellStyle(style);
RichTextString str = new HSSFRichTextString("富文本");
// font2将覆盖font1
str.applyFont(6, 13, font2);
cell.setCellValue(str);

要将不同的字体Font应用于富文本字符串的不同部分一般采用第二种方法

package hssf.sheet.richtextstring;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExportHSSFRichTextString {
    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\test.xls");
        if (file.exists()) {
            file.delete();
        }
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.xls"));
            exportExcel(out);
        } finally {
            out.close();
        }
    }

    private static void exportExcel(BufferedOutputStream out) throws IOException {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("富文本");
        sheet.setColumnWidth(2, 150*256);
        Row row = sheet.createRow(5);
        Cell cell = row.createCell(2);

        CellStyle style = workbook.createCellStyle();
        cell.setCellStyle(style);
        HSSFRichTextString str = new HSSFRichTextString("富文本上标 字符串下标 水平删除线 下划线");

        /**********************************第一个字体Font:富文本0-3******************************************************/
        // 在workbook中创建一个字体
        Font font1 = workbook.createFont();
        // 设置字体为粗体
        font1.setBold(true);
        // 设置字体的字符集 - 默认字体集
        font1.setCharSet(Font.DEFAULT_CHARSET);
        // 设置字体的高度 - 以1pt的1/20位单位
        font1.setFontHeightInPoints((short)40);
        // 设置字体的名字
        font1.setFontName("宋体");
        // 设置文字为斜体
        font1.setItalic(false);
        // 使用水平删除线
        font1.setStrikeout(true);
        // 设置字体颜色为默认黑色
        font1.setColor(Font.COLOR_RED);
        style.setFont(font1);

        /**********************************第二个字体Font: 上标3-5******************************************************/
        Font font2 = workbook.createFont();
        // 设置上标字体高度为30pt
        font2.setFontHeightInPoints((short)20);
        // 设置为上标
        font2.setTypeOffset(Font.SS_SUPER);
        str.applyFont(3, 5, font2);

        /**********************************第三个字体Font: 字符串6-9******************************************************/
        Font font3 = workbook.createFont();
        // 设置字体高度 - 以1pt为单位, 设置字体为60pt
        font3.setFontHeightInPoints((short)40);
        font3.setBold(true);
        // 设置字体的字符集 - ANSI字符集
        font3.setCharSet(Font.ANSI_CHARSET);
        // 设置字体颜色为深红色
        font3.setColor(Font.COLOR_RED);
        str.applyFont(6, 9, font3);

        /**********************************第四个字体Font: 下标9-11******************************************************/
        Font font4 = workbook.createFont();
        // 设置为下标
        font4.setTypeOffset(Font.SS_SUB);
        // 设置下 标字体高度为30pt
        font4.setFontHeightInPoints((short)20);
        str.applyFont(9, 11, font4);

        /**********************************第五个字体Font: 水平删除线12-17******************************************************/
        Font font5 = workbook.createFont();
        // 设置下 标字体高度为30pt
        font5.setFontHeightInPoints((short)30);
        font5.setColor(Font.COLOR_RED);
        font5.setStrikeout(true);
        str.applyFont(12, 17, font5);

        /**********************************第六个字体Font: 下划线18-21******************************************************/
        Font font6 = workbook.createFont();
        // 设置下 标字体高度为30pt
        font6.setFontHeightInPoints((short)30);
        font6.setColor(Font.COLOR_RED);
        font6.setItalic(true);
        // 设置字体双下划线
        font6.setUnderline(Font.U_DOUBLE);
        str.applyFont(18, 21, font6);

        cell.setCellValue(str);
        workbook.write(out);
    }
}

这里写图片描述

3.XSSFRichTextString

3.1 共享字符串

工作簿Workbook大多数字符串具有在单元格级别的格式化样式,即单元格中的整个字符串具有相同的格式应用。 在这些情况下,单元格的格式存储在styles(对于一个styles.xml)中,单元格的字符串可以跨工作表共享 (sharedStrings.xml)。以下代码说明了该示例。

package hssf.sheet.richtextstring;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 共享富文本字符串
 * */
public class ExportXSSFRichTextSTring_shard {
    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\test.xlsx");
        if (file.exists()) {
            file.delete();
        }
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.xlsx"));
            exportExcel(out);
        } finally {
            out.close();
        }
    }

    private static void exportExcel(BufferedOutputStream out) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("共享字符串");
        sheet.setColumnWidth(0, 30*256);
        sheet.setColumnWidth(1, 30*256);
        sheet.setColumnWidth(2, 30*256);

        Row row = sheet.createRow(0);
        row.setHeightInPoints(20);
        row.createCell(0).setCellValue(new XSSFRichTextString("Apache POI"));
        row.createCell(1).setCellValue(new XSSFRichTextString("Apache POI"));
        row.createCell(2).setCellValue(new XSSFRichTextString("Apache POI"));

        workbook.write(out);
    }
}
上述3个单元格都使用了工作簿Workbook中缓存的共享字符串 - Apache POI 

这里写图片描述
这里写图片描述
这里写图片描述

3.2 非共享字符串

工作簿中的富文本字符串XSSFRichTextString可能具有比单元格级别更细粒度的样式,即可以设置多个样式作用与富文本字符串的不同部分。在这种情况下,样式和文本一起存储在string table中,并被视为工作簿中的唯一条目(entry):

package hssf.sheet.richtextstring;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExportXSSFRichTextString_unique {
    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\Administrator\\Desktop\\test.xlsx");
        if (file.exists()) {
            file.delete();
        }
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test.xlsx"));
            exportExcel(out);
        } finally {
            out.close();
        }
    }

    /**
     * @param out
     * @throws IOException
     */
    private static void exportExcel(BufferedOutputStream out) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("共享字符串");
        sheet.setColumnWidth(0, 30*256);
        sheet.setColumnWidth(1, 30*256);
        sheet.setColumnWidth(2, 30*256);

        Row row = sheet.createRow(0);
        row.setHeightInPoints(20);

        RichTextString s1 = new XSSFRichTextString("Apache POI");
        Font font1 = workbook.createFont();
        font1.setBold(true);
        font1.setColor(IndexedColors.RED.getIndex());
        font1.setFontHeightInPoints((short)20);
        s1.applyFont(font1);
        row.createCell(0).setCellValue(s1);

        RichTextString s2 = new XSSFRichTextString("Apache POI");
        Font font2 = workbook.createFont();
        font2.setItalic(true);
        font2.setColor(IndexedColors.BLUE.getIndex());
        font2.setFontHeightInPoints((short)20);
        s2.applyFont(font2);
        row.createCell(1).setCellValue(s2);

        RichTextString s3 = new XSSFRichTextString("Apache POI");
        Font font3 = workbook.createFont();
        font3.setStrikeout(true);
        font3.setColor(IndexedColors.GREEN.getIndex());
        font3.setFontHeightInPoints((short)20);
        s3.applyFont(font3);
        row.createCell(2).setCellValue(s3);

        workbook.write(out);
    }
}

这里写图片描述
这里写图片描述
这里写图片描述

### 使用 EasyExcel 读取 Excel 中的富文本内容 在处理 Excel 文件时,尤其是当文件中含有复杂的单元格格式或富文本内容时,使用 EasyExcel 可能会面临一些挑战。当前版本的 EasyExcel 主要专注于高效地读写大规模的数据,在官方文档和支持的功能列表里并没有特别提到对于富文本的支持[^1]。 然而,如果确实有需求读取带有富文本样式的单元格内容,则可以考虑结合其他库来完成这一目标。例如,Apache POI 是一个广泛使用的 Java 库,它能够更全面地支持 Microsoft Office 文档的各种特性,包括但不限于字体颜色、粗体、斜体等样式设置以及超链接等功能[^2]。 下面是一个简单的例子展示如何利用 Apache POI 来读取含有富文本格式的 Excel 单元格: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; public class RichTextReadExample { public static void main(String[] args) throws IOException { try (FileInputStream fis = new FileInputStream("path/to/excel/file.xlsx"); Workbook workbook = new XSSFWorkbook(fis)) { Sheet sheet = workbook.getSheetAt(0); Row row = sheet.getRow(0); // 获取第1行 Cell cell = row.getCell(0); // 获取A列的第一个单元格 if(cell != null && cell.getCellType() == CellType.STRING){ RichTextString richText = cell.getRichStringCellValue(); System.out.println("Plain text: " + richText.getString()); for(int i=0; i<richText.numFormattingRuns();i++){ int start = richText.getIndexOfFormattingRun(i); int end = start + richText.lengthOfFormattingRun(i); Font fontUsedInThisPart = richText.getFontAtIndex(start); System.out.printf("From %d to %d uses ",start,end); if(fontUsedInThisPart!=null){ System.out.print("font with "); short boldWeight = fontUsedInThisPart.getBoldweight(); boolean isItalic = fontUsedInThisPart.getItalic(); byte underlineStyle = fontUsedInThisPart.getUnderline(); if(boldWeight>Font.BOLDWEIGHT_NORMAL){ System.out.print("bold, "); } if(isItalic){ System.out.print("italic, "); } switch(underlineStyle){ case Font.U_SINGLE -> System.out.print("single underlined, "); case Font.U_DOUBLE -> System.out.print("double underlined, "); default->System.out.print("no underline, "); } System.out.println("color index "+fontUsedInThisPart.getColor()); }else{ System.out.println("default style."); } } } workbook.close(); } } } ``` 这段代码展示了如何通过 `getRichStringCellValue()` 方法获取到 `RichTextString` 对象,并遍历其内部的不同格式化片段(即不同的文字风格)。这允许开发者提取出具体的字符范围及其对应的格式属性,从而实现对富文本内容的有效解析和处理[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值