1 依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.34</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.3.0</version>
</dependency>
2 代码
package com.xu.excel;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class LightTest {
public static void main(String[] args) {
ExcelWriter writer = new ExcelWriter("2.xlsx");
Workbook workbook = writer.getWorkbook();
Sheet sheet = writer.getSheet();
Row headerRow = sheet.createRow(0);
Cell header = headerRow.createCell(0);
header.setCellValue("表头名称");
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
header.setCellStyle(style);
sheet.setColumnWidth(0, 30 * 256);
String light = "高亮";
List<String> texts = new ArrayList<>();
texts.add("Hello Hutool World");
texts.add("测试");
texts.add("测试某一段高亮");
texts.add("高亮");
texts.add("这个也需要高亮一下");
texts.add("这个不要");
int i = 1;
for (String text : texts) {
Row row = sheet.createRow(i);
Cell cell = row.createCell(0);
i++;
RichTextString richText = workbook.getCreationHelper().createRichTextString(text);
if (StrUtil.contains(text, light)) {
Font highlightFont = workbook.createFont();
highlightFont.setBold(true);
highlightFont.setColor(IndexedColors.YELLOW.getIndex());
int start = text.indexOf(light);
richText.applyFont(start, (start) + light.length(), highlightFont);
}
cell.setCellValue(richText);
}
writer.flush();
writer.close();
}
}
结果
