관리 메뉴

개발 기록이

[Java] POI 엑셀 다운로드 하기(셀 병합) 본문

웹 개발/Back-end

[Java] POI 엑셀 다운로드 하기(셀 병합)

studyingbackhoe 2026. 2. 17. 14:26

springboot, java, gradle, IntelliJ 환경에서 엑셀 다운로드하는 방법에 대해 알아보자.

 

1. 생성할 엑셀 형태 지정

0행 0열 1 ~ 2열 3 ~ 7열 8 열 9 열
1행 No 도서상세정보 도서대여자 대여상태 비고
제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형

 

 

2. 병합되는 열 정리

No, 대여상태, 비고는 2행이 병합되고 도서상세정보, 도서대여자는 각각 2열, 5열이 병합되어야 한다.

 

3. build.gradle에 엑셀 다운로드를 위한 POI 의존성 추가

dependencies {
	implementation 'org.apache.poi:poi-ooxml:5.2.5'
}

 

4. 엑셀 파일과 시트 생성(Workbook, Sheet)

XSSFWorkbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("도서대여현황");
  • XSSF : .xlsx 형식을 지원
  • CellStyle : 엑셀의 폰트, 정렬, 색상, 테두리를 설정할 수 있음
  • 스타일 지정
// 헤더 스타일
CellStyle headStyle = workbook.createCellStyle();

headStyle.setAlignment(HorizontalAlignment.CENTER); 
headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headStyle.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headStyle.setBorderTop(BorderStyle.THIN);
headStyle.setBorderBottom(BorderStyle.THIN);
headStyle.setBorderLeft(BorderStyle.THIN);
headStyle.setBorderRight(BorderStyle.THIN);


// 데이터 영역 스타일
CellStyle bodyStyle = workbook.createCellStyle();

bodyStyle.setAlignment(HorizontalAlignment.CENTER);
bodyStyle.setVerticalAlignment(VerticalAlignment.CENTER); 
bodyStyle.setBorderTop(BorderStyle.THIN);
bodyStyle.setBorderBottom(BorderStyle.THIN);
bodyStyle.setBorderLeft(BorderStyle.THIN);
bodyStyle.setBorderRight(BorderStyle.THIN);
  • 좌표 기준: CellRangeAddress(시작행, 끝행, 시작열, 끝열)
  • 세로 병합: No, 대여상태처럼 하위 항목이 없는 경우 위아래 칸을 합친다.
  • 가로 병합: 도서상세정보(2칸), 도서 대여자(5칸)처럼 소분류가 있는 경우 옆으로 합친다.

 

(주의⚠️) 0부터 시작

// 행 생성 (2개 행)
Row row0 = sheet.createRow(0);
Row row1 = sheet.createRow(1);

 

 

엑셀 헤더 부분 코드는 다음과 같다.

row0.getCell(0).setCellValue("No"); //0행 0열 데이터값
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));

row0.getCell(1).setCellValue("도서상세정보"); // 0행 1열 데이터값
sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 2)); 
row1.getCell(1).setCellValue("제목"); // 1행 1열 데이터값
row1.getCell(2).setCellValue("저자"); // 1행 2열 데이터값

row0.getCell(3).setCellValue("도서 대여자"); // 0행 3열 데이터값
sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 7));
row1.getCell(3).setCellValue("이름");     // 1행 3열 데이터값
row1.getCell(4).setCellValue("전화번호"); // 1행 4열 데이터값
row1.getCell(5).setCellValue("회원등급"); // 1행 5열 데이터값
row1.getCell(6).setCellValue("회원가입일시"); // 1행 6열 데이터값
row1.getCell(7).setCellValue("관심유형"); // 1행 7열 데이터값

row0.getCell(8).setCellValue("대여상태"); // 0행 8열 데이터값
sheet.addMergedRegion(new CellRangeAddress(0, 1, 8, 8)); 

row0.getCell(9).setCellValue("비고"); // 0행 9열 데이터값
sheet.addMergedRegion(new CellRangeAddress(0, 1, 9, 9));

 

 

이중 셀 병합 부분을 상세히 살펴보면 다음과 같다. *CellRangeAddress(시작행, 끝행, 시작열, 끝열) 

 

1) sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));

    0행 0열 1행 0열을 합친다.

  0열 1 열 2 열 3 열 4 열 5 열 6 열 7 열 8 열 9 열
0행 No 도서상세정보   도서대여자         대여상태 비고
1행   제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형    

 

 

2) sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 2)); 

    0행 1열 0행 2열을 합친다.

  0열 1 열 2 열 3 열 4 열 5 열 6 열 7 열 8 열 9 열
0행 No 도서상세정보   도서대여자         대여상태 비고
1행   제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형    

 

 

3) sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 7));

    0행 3열 0행 7열을 합친다.

  0열 1 열 2 열 3 열 4 열 5 열 6 열 7 열 8 열 9 열
0행 No 도서상세정보   도서대여자         대여상태 비고
1행   제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형    

 


4) sheet.addMergedRegion(new CellRangeAddress(0, 1, 8, 8));

    0행 8열 1행 8열을 합친다.

  0열 1 열 2 열 3 열 4 열 5 열 6 열 7 열 8 열 9 열
0행 No 도서상세정보   도서대여자         대여상태 비고
1행   제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형    

 


5) sheet.addMergedRegion(new CellRangeAddress(0, 1, 9, 9));

    0행 9열 1행 9열을 합친다.

  0열 1 열 2 열 3 열 4 열 5 열 6 열 7 열 8 열 9 열
0행 No 도서상세정보   도서대여자         대여상태 비고
1행   제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형    

 

*최종 

  0열 1열 2열 3열 4열 5열 6열 7열 8열 9열
0행 No 도서상세정보 도서대여자 대여상태 비고
1행 제목 저자 이름 연락처 회원등급 회원가입일시 관심도서유형

 

 

5. 엑셀 데이터 넣기

String[] sampleData = {"1", "자바의 정석 기초편", "남궁성", "홍길동", "010-1234-5678", "VIP", "2024-05-01 14:00", "IT/프로그래밍", "대여중", "연체 주의 바랍니다."};

for(int i=0; i < sampleData.length; i++) {
  Cell cell = bodyRow.createCell(i);
  cell.setCellValue(sampleData[i]);
  cell.setCellStyle(bodyStyle);
}

// 셀 간격(너비) 수동 및 자동 조절
for (int i = 0; i <= 9; i++) {
  sheet.autoSizeColumn(i); // 먼저 내용에 맞게 자동 조절
  int currentWidth = sheet.getColumnWidth(i);
  sheet.setColumnWidth(i, currentWidth + 1500);
}

 

 

6. 만들어진 엑셀 다운로드 하기

String fileName = "책대여현황.xlsx";
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
workbook.write(resp.getOutputStream());
workbook.close();

 

 

(엑셀 다운로드 화면)

 


참고: OpenAI ChatGPT (https://openai.com)