Java/Common
Java POI Excel을 이용하여 셀 안의 특정 문자열만 색깔 바꾸기
조영래
2022. 4. 25. 11:19
프로젝트 요구사항 중에서 엑셀의 셀 안의 내용중에서 특정 문자열만 하이라이트 하고 싶은 것이 있었다.
예를 들면 "문자열 중에 하이라이트 합니다." 처럼.
구글링을 해보니 작업이 가능하였다.
// 빈 Workbook 생성
XSSFWorkbook workbook = new XSSFWorkbook();
// 빈 Sheet를 생성
XSSFSheet sheet = workbook.createSheet("DATA");
// 색상 지정
XSSFFont fontRed = (XSSFFont) sheet.getWorkbook().createFont();
fontRed.setColor(Font.COLOR_RED);
// XSSFFont fontBlue = (XSSFFont) sheet.getWorkbook().createFont();
// fontRed.setColor(IndexedColors.GREEN.getIndex());
XSSFRow row = sheet.createRow(1);
XSSFCell cell = row.createCell(1);
XSSFCellStyle defaultStyle = cell.getCellStyle();
String data = "문자열 중에 하이라이트 합니다.";
XSSFRichTextString dataRich = new XSSFRichTextString(data);
String keyword = "하이라이트";
int index = data.indexOf(keyword);
dataRich.applyFont(index, index + keyword.length(), fontRed);
cell.setCellValue(dataRich);
cell.setCellStyle(defaultStyle);
try {
FileOutputStream out = new FileOutputStream(new File("c:\\temp", "newExcel.xlsx"));
workbook.write(out);
out.close();
}
catch (IOException e) {
e.printStackTrace();
}