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

前言: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);

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值