欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Excel给同一单元格设置不同颜色的字体

程序员文章站 2022-07-13 21:52:37
...

【环境】

poi-ooxml 4.0.1、java 8

【核心代码】

XSSFRichTextString value = new XSSFRichTextString("红色黑色");
value.applyFont(0, 2, redFont);

【完整代码】

package excel.write;

import java.io.File;
import java.io.FileOutputStream;

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

public class ExcelRichTextTest {
    public static void main(String[] args) {
        String filePath =
                "E:\\tmp\\test\\excelTest\\richText_" + System.currentTimeMillis() + ".xlsx";
        File folder = new File(filePath.substring(0, filePath.lastIndexOf(File.separator)));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        Workbook wb = null;
        FileOutputStream out = null;
        try {
            wb = new XSSFWorkbook();
            Sheet sheet = wb.createSheet();
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);

            XSSFRichTextString value = new XSSFRichTextString("红色黑色");

            Font redFont = wb.createFont();
            redFont.setColor(Font.COLOR_RED);
            redFont.setBold(true);
            redFont.setFontName("宋体");
            // 给[0, 2)位置设置以上格式
            value.applyFont(0, 2, redFont);

            Font blackFont = wb.createFont();
            blackFont.setColor(Font.COLOR_NORMAL);
            blackFont.setBold(true);
            blackFont.setFontName("宋体");
            value.applyFont(2, value.length(), blackFont);

            cell.setCellValue(value);

            out = new FileOutputStream(filePath);
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (wb != null) {
                    wb.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}

【效果】

Excel给同一单元格设置不同颜色的字体

【说明】

Excel显示的效果确实为红色+宋体,但是在字体属性这一块显示的是默认的,双击单元格后字体属性就显示正常了。

Excel给同一单元格设置不同颜色的字体

做了双击单元格操作之后,点击关闭Excel,会提示是否要保存,选择保存,然后再次打开Excel,字体属性这一块就显示对了。

Excel给同一单元格设置不同颜色的字体

【猜测】

有可能是POI写的Excel文件内部格式和软件写的不同,打开软件后的字体属性未能正确读取到这些格式(但显示是对的),然后双击单元格后,软件应该修改了Excel文件内部的格式,保存后就能正常读取了。