需求
导出的Excel标题化学元素符号要显示下标,例如H2
实现思路
- 如何使生成的Excel中对一个单元格的不同内容显示不同样式
POI中提供applyFont函数,可根据索引指定Font
RichTextString richTextString5_ = new XSSFRichTextString("H2");
Font font = workbook.createFont();
font.setTypeOffset(Font.SS_SUB);
richTextString5_.applyFont(1, 2, font);
- 试图copy进项目
原有项目用的EasyExcel 3.3.1,JDK8。
RichTextString richTextString = creationHelper.createRichTextString("H2");
Font font = workbook.createFont();
font.setBold(false);
font.setTypeOffset(Font.SS_SUB);
richTextString.applyFont(0, 1, font);
font.setItalic(true);
font.setColor(IndexedColors.RED.index);
font.setTypeOffset(Font.SS_SUB);
sheet.getRow(0).createCell(1).setCellValue(richTextString);
但是能显示H2,样式怎么也不生效。猜测和EasyExcel的doWrite方法有关?因为写了一个POI最简单的导出带RichTextString的Excel有样式。
- 决定使用POI
RichTextString richTextString5_ = new XSSFRichTextString(cell_5.getStringCellValue());
Font font = book.createFont();
font.setTypeOffset(Font.SS_SUB);
richTextString5_.applyFont(richTextString5_.length()-1, richTextString5_.length(), font);
cell_5.setCellValue(richTextString5_);
- 搬运原本在
AbstractVerticalCellStyleStrategy#headCellStyle下的样式
XSSFCellStyle cellStyle = (XSSFCellStyle) book.createCellStyle();
XSSFFont fb = (XSSFFont) book.createFont();
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
fb.setFontHeightInPoints((short)12);
cellStyle.setFont(fb);
cell_1.setCellStyle(cellStyle);
POI版本4.1.2,但是样式怎么也不生效
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
- 加上
FillPatternType.SOLID_FOREGROUND样式生效。
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
注意点:单元格设置背景颜色,需要设置setFillForegroundColor 参数,还需要再设置一下setFillPattern,在setFillPattern中添加FillPatternType.SOLID_FOREGROUND即可