如何使用apache poi更改Excel表单的同一单元格中的特定文本颜色? [英] How to change the specific text color in a same cell of excel sheet using apache poi?

查看:377
本文介绍了如何使用apache poi更改Excel表单的同一单元格中的特定文本颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何改变excel中单元格的特定文本的颜色。
我使用apache poi,我可以找出改变整个单元格的文本颜色。但是我只想要一个特定的文本。



例如:单元格A1有Hello World
我希望Hello成为蓝色,World绿色。
我该怎么做?

解决方案

关键是使用 HSSFRichTextString 对象来设置单元格的值。此对象具有 applyFont 方法,它接受startingIndex,endingIndex和Font。因此,您可以创建具有所需颜色的字体,然后使用applyFont()将其应用于单元格值的部分。



这里是一些代码示例,完全未经测试):

  //设置一个包含单元格的基本工作表
HSSFWorkbook wb = new HSSFWorkbook );
HSSFSheet sheet = wb.createSheet(sheet1);
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);

//设置字体
HSSFFont blueFont = workbook.createFont();
blueFont.setColor(HSSFColor.BLUE.index);

HSSFFont greenFont = workbook.createFont();
greenFont.setColor(HSSFColor.GREEN.index);

//创建单元格样式并为其分配第一个字体
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(blueFont);

//将样式分配给单元格
cell.setCellStyle(style);

//通过应用不同的字体来覆盖您要
//颜色不同的文本的部分。
HSSFRichTextString richString = new HSSFRichTextString(Hello,World!);
richString.applyFont(6,13,greenFont);
cell.setCellValue(richString);


Does anyone know how to change the color of the particular text of a cell in excel. I am using apache poi and I could find out to change the text color of entire cell. But I want only a particular text.

Eg: Cell A1 has Hello World I want "Hello" to be in blue and "World" to be in green. How do I do this?

解决方案

The key is using the HSSFRichTextString object to set the value of the cell. This object has an applyFont method which accepts a startingIndex, endingIndex and a Font. Thus, you can create fonts having the colors you want, then apply them to parts of the cell value using applyFont().

Here is some example code I cobbled together (completely untested):

// Set up a rudimentary worksheet with a cell in it
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet1");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);

// Set up fonts
HSSFFont blueFont = workbook.createFont();
blueFont.setColor(HSSFColor.BLUE.index);

HSSFFont greenFont = workbook.createFont();
greenFont.setColor(HSSFColor.GREEN.index);

// create a cell style and assign the first font to it
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(blueFont);

// assign the style to the cell
cell.setCellStyle(style);

// override the parts of the text that you want to
// color differently by applying a different font.
HSSFRichTextString richString = new HSSFRichTextString("Hello, World!");
richString.applyFont(6, 13, greenFont);
cell.setCellValue(richString);

这篇关于如何使用apache poi更改Excel表单的同一单元格中的特定文本颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆