有谁知道如何在 excel 中更改单元格特定文本的颜色。 我正在使用 apache poi,我可以找到更改整个单元格的文本颜色的方法。但我只想要一个特定的文本。
例如:单元格 A1 有 Hello World 我希望“Hello”为蓝色,“World”为绿色。 我该怎么做?
最佳答案
关键是使用 HSSFRichTextString对象来设置单元格的值。这个对象有一个 applyFont接受 startingIndex、endingIndex 和 Font 的方法。因此,您可以创建具有所需颜色的字体,然后使用 applyFont() 将它们应用于部分单元格值。
这是我拼凑的一些示例代码(完全未经测试):
// 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);
关于java - 如何使用 apache poi 更改 excel 表的同一单元格中的特定文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15456884/