java POI excel 导出复合样式(一个单元格两个字体)

2023-06-12,,

前言:java poi 导出 excel 时,需要设置一个单元格有多个字体样式,有点类似于富文本。

想要达到的效果(一个单元格里):

我使用的 poi 版本是

        <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>

具体实现:

工具类方法:

/**
* 设置值和样式,富文本 复合样式(一个单元格多个字体)
* @param cell 当前单元格
* @param wholeStr 整个字符串
* @param strArray 字符串分割的数组
* @param strFontList 字符串分割后一一对应的字体
*/
public static void setRichTextCellValue(Cell cell, String wholeStr, String[] strArray, List<Font> strFontList){
HSSFRichTextString hssfRichTextString = new HSSFRichTextString(wholeStr);
int strLength = 0;
for(int i = 0; i < strArray.length; i++){
hssfRichTextString.applyFont(strLength, strLength + strArray[i].length(), strFontList.get(i));
strLength = strArray[i].length();
}
cell.setCellValue(hssfRichTextString);
}

设置第0行第0列的代码:

        List<Font> strFontList = new ArrayList<>();
strFontList.add(GenerateFontUtil.getRedFont(workbook));
Font font = GenerateFontUtil.getCommonFont(workbook);
font.setFontHeightInPoints((short) 14);
strFontList.add(font);
GenerateCellStyleUtil.setRichTextCellValue(sheet.getRow(0).getCell(0), "红色字体 黑色字体"
, new String[]{"红色字体", " 黑色字体"}, strFontList);

java POI excel 导出复合样式(一个单元格两个字体)的相关教程结束。

《java POI excel 导出复合样式(一个单元格两个字体).doc》

下载本文的Word格式文档,以方便收藏与打印。