web developer

[java] poi excel 메모(comment) 생성 및 위치조정 본문

Language/Java

[java] poi excel 메모(comment) 생성 및 위치조정

trueman 2024. 2. 29. 17:44
728x90
728x90

엑셀 다운로드 시 메모 생성하기


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelCommentExample {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 데이터 삽입 및 코멘트 추가
        for (int i = 0; i < 10; i++) {
            Row row = sheet.createRow(i);
            Cell cell = row.createCell(0);
            cell.setCellValue("Data " + i);

            // 특정 조건에 따라 코멘트를 추가할 셀 선택
            if (i % 2 == 0) {
                // 코멘트 생성
                addCommentToCell(workbook, sheet, cell, i);
            }
        }

        // 엑셀 파일 저장
        try (FileOutputStream fileOut = new FileOutputStream("example.xlsx")) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

메모의 크기를 '하드코딩'으로 조정


장점

  1. 우측행(ex AA행)에 숨긴 처리된 부분이 있는 경우 Z행에서 메모가 표출되면, 숨긴 처리된 행으로 인하여 메모가 짤린 상태로 표출되겠지만, 하드코딩으로 A행에 메모를 위치시키면 어느 정도의 메모 크기라면 문제없이 표출될 수 있다.
  2. 왼쪽행(ex A행)에 숨긴 처리된 있는 경우 A행에 메모가 표출되면 메모가 짤리게 된다. 이런 경우에는 B행 이후로 위치를 조정해주면 된다.

단점 

  1. 마우스오버시 해당 셀의 위치에 맞게 메모가 생성된 것처럼 보이지만, 편집 클릭 시 하드코딩된 해당 위치에 위치한다.
private static void addCommentToCell(Workbook workbook, Sheet sheet, Cell cell, int rowIndex) {
    // 코멘트 추가
    CreationHelper creationHelper = workbook.getCreationHelper();
    Drawing<?> drawing = sheet.createDrawingPatriarch();
    ClientAnchor anchor = creationHelper.createClientAnchor();

    // 코멘트 위치 지정
    anchor.setCol1(0); // 주석이 시작되는 셀의 열 인덱스 [가로]
    anchor.setCol2(7); // 주석이 끝나는 셀의 열 인데스   [가로]
    anchor.setRow1(0); // 주석이 시작되는 셀의 행 인덱스 [세로]
    anchor.setRow2(2); // 주석이 끝나는 셀의 행 인덱스   [세로]

    // 코멘트 생성 및 내용 설정
    Comment comment = drawing.createCellComment(anchor);
    RichTextString str = creationHelper.createRichTextString("Comment for Data " + rowIndex);
    comment.setString(str);

    // 생성된 코멘트 적용
    cell.setCellComment(comment);
}

 

메모 크기를 '동적'으로 조정


장점

  1. 해당 셀의 위치에 맞게 메모가 생성된다.

단점

  1. 우측행(ex AA행)에 숨긴 처리할 부분이 있는 경우 Z행에서 메모가 표출되면, 숨긴 처리된 행으로 인하여 메모가 짤린 상태로 표출된다.
public static void addCommentToCell(Cell cell, String commentText, String author) {
	// 엑셀 주석 객체 생성
	CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper();
	Drawing<?> drawing = cell.getSheet().createDrawingPatriarch();
	ClientAnchor anchor = factory.createClientAnchor();

	// 주석 위치 설정
	anchor.setCol1(cell.getColumnIndex());
	anchor.setCol2(cell.getColumnIndex() + 1);

	// 텍스트의 길이에 따라 주석의 크기를 동적으로 조정
	int textLength = commentText.length();
	int rowCount = (textLength / 30) + 1; // 예상 줄 수
	anchor.setRow1(cell.getRowIndex());
	anchor.setRow2(cell.getRowIndex() + rowCount); // 텍스트 길이에 따라 동적으로 조정

	// 주석 생성
	Comment comment = drawing.createCellComment(anchor);
	RichTextString str = factory.createRichTextString(commentText);
	comment.setString(str);

	// 주석 작성자 설정
	if (author != null && !author.isEmpty()) {
		comment.setAuthor(author);
	}

	// 셀에 주석 연결
	cell.setCellComment(comment);
}
728x90
728x90
Comments