有沒有人知道如何改變excel中單元格特定文本的顏色。 我正在使用apache poi,我可以找出更改整個單元格的文本顏色。但我只想要一個特定的文本。如何使用apache poi更改excel表單的同一單元格中的特定文本顏色?
例如:單元格A1有Hello World 我希望「你好」是藍色,「世界」是綠色。 我該怎麼做?
有沒有人知道如何改變excel中單元格特定文本的顏色。 我正在使用apache poi,我可以找出更改整個單元格的文本顏色。但我只想要一個特定的文本。如何使用apache poi更改excel表單的同一單元格中的特定文本顏色?
例如:單元格A1有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);
有趣的是,如果你想覆蓋你好的顏色,這是行不通的。如果您修改World,完全相同的代碼片段可以工作!Hello的顏色被重寫了alrite,但World失去了它的風格。 – Achow 2014-12-22 02:12:12
如果您明確應用了字體,它就是固定的 - richString.applyFont(blueFont); richString.applyFont(2,5,greenFont); – Achow 2014-12-22 02:20:53
對於xlsx文件,有一個等同的[XSSFRichTextString](https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRichTextString.html),它的工作方式相同。 – jamsandwich 2016-08-11 05:41:22
首先創建一個樣式
//////////////////////Excel Header Style/////////////////////////
HSSFCellStyle headerlabelcs = wb.createCellStyle();
headerlabelcs.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
headerlabelcs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headerlabelcs.setBorderLeft((short)1);
headerlabelcs.setBorderRight((short)1);
HSSFFont headerlabelfont = wb.createFont();
headerlabelfont.setFontHeightInPoints((short)12);
headerlabelfont.setFontName("Calibri");
headerlabelfont.setColor(HSSFColor.BLACK.index);
headerlabelfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerlabelcs.setFont(headerlabelfont);
//////////////////////Excel Header Style/////////////////////////
添加那麼這行會在你的代碼中加入
sheet.getRow(rowIndex).getCell(0).setCellStyle(headerlabelcs);
該解決方案不會執行OP要求的操作。他希望將單個單元格中的部分文本設置爲兩種不同的顏色。 – 2013-03-18 15:35:02
然後根據文字改變風格 – Biswajit 2013-03-18 17:40:18
@BrianRogers謝謝你確認一個單元格可以有多種顏色。 – 2013-03-17 03:26:57