如何使用apache poi在excel表单的同一个单元格中更改特定的文本颜色?
有没有人知道如何改变Excel中单元格的特定文本的颜色。 我正在使用Apache poi,我可以找出更改整个单元格的文本颜色。 但是我只想要一个特定的文本。
例如:单元格A1有Hello World,我希望“你好”是蓝色的,“世界”是绿色的。 我该怎么做呢?
关键是使用HSSFRichTextString对象来设置单元格的值。 这个对象有一个applyFont方法,它接受一个startingIndex,endingIndex和一个Font。 因此,您可以创build具有所需颜色的字体,然后使用applyFont()将它们应用于单元格的部分值。
下面是我拼凑在一起的一些示例代码(完全未经testing):
// 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);
首先创build一个风格
//////////////////////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);
- Apache POI专注于生成的Excel文件中的特定单元格
- 在Apache POI中使用Excel PERCENTILE函数
- 在Android中使用Apache POI时的兼容性问题
- 在服务器上创buildXLS文件并返回到客户端,而不保存java中服务器上的文件
- 如何从Web上的边桌数据打印列标题与WebDriver优秀
- 如何在Java中使用apache poi将数据validation添加到Excel表单的整个列?
- 如何使用Apache POI(SXSSF)为特定单元格设置数据(数字)格式区域设置?
- 在Java中读取巨大的Excel文件(500K行)
- 有没有办法使用Apache POI来读取.xls和.xlsx文件?