From e90505d1901f8d4c13706ba45d1aa212b751e7ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=A3=BC=EC=9A=B0=EC=84=B1?= Date: Thu, 26 Jun 2025 15:22:37 +0900 Subject: [PATCH] =?UTF-8?q?Excel=EB=8B=A4=EC=9A=B4=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../application/util/ExcelWriterUtil.java | 134 ++++++++++++++++++ .../application/util/model/ExcelSheetDto.java | 45 ++++++ .../web/GetExcelMultiSheetController.java | 124 ++++++++++++++++ 3 files changed, 303 insertions(+) create mode 100644 admin/src/main/java/app/module/admin/config/application/util/ExcelWriterUtil.java create mode 100644 admin/src/main/java/app/module/admin/config/application/util/model/ExcelSheetDto.java create mode 100644 admin/src/main/java/app/module/admin/usecase/excel/getExcelMultilSheet/adapters/web/GetExcelMultiSheetController.java diff --git a/admin/src/main/java/app/module/admin/config/application/util/ExcelWriterUtil.java b/admin/src/main/java/app/module/admin/config/application/util/ExcelWriterUtil.java new file mode 100644 index 00000000..032070d4 --- /dev/null +++ b/admin/src/main/java/app/module/admin/config/application/util/ExcelWriterUtil.java @@ -0,0 +1,134 @@ +package app.module.admin.config.application.util; + +import app.module.admin.config.application.util.model.ExcelSheetDto; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Component; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; + + +@Component +public class ExcelWriterUtil { + public static byte[] writeExcel(List sheets) { + try (Workbook workbook = new XSSFWorkbook()) { + CellStyle bodyStyle = createBodyStyle(workbook); + CellStyle commaStyle = createCommaStyle(workbook); + + for (ExcelSheetDto sheetDto : sheets) { + Sheet sheet = workbook.createSheet(sheetDto.getSheetName()); + List headers = sheetDto.getHeaders(); + List> dataRows = sheetDto.getData(); + + // 헤더 작성 + Row headerRow = sheet.createRow(0); + for (int col = 0; col < headers.size(); col++) { + String headerText = headers.get(col); + + IndexedColors bgColor = sheetDto.getHeaderBgColors() != null + ? sheetDto.getHeaderBgColors().getOrDefault(col, IndexedColors.GREY_25_PERCENT) + : IndexedColors.GREY_25_PERCENT; + + CellStyle headerStyle = createHeaderStyle(workbook, bgColor); + + Cell cell = headerRow.createCell(col); + cell.setCellValue(headerText); + cell.setCellStyle(headerStyle); + } + + // 데이터 작성 + for (int r = 0; r < dataRows.size(); r++) { + Row row = sheet.createRow(r + 1); + List rowData = dataRows.get(r); + for (int c = 0; c < rowData.size(); c++) { + Cell cell = row.createCell(c); + String value = rowData.get(c); + if (sheetDto.getCommaColumns() != null && + sheetDto.getCommaColumns().contains(c) && + isNumeric(value)) { + cell.setCellValue(Double.parseDouble(value)); + cell.setCellStyle(commaStyle); + } else { + cell.setCellValue(value); + cell.setCellStyle(bodyStyle); + } + } + } + + // 컬럼 너비 수동 계산 + for (int col = 0; col < headers.size(); col++) { + int maxLength = getByteLength(headers.get(col)); + for (List rowData : dataRows) { + if (col < rowData.size()) { + int length = getByteLength(rowData.get(col)); + if (length > maxLength) { + maxLength = length; + } + } + } + sheet.setColumnWidth(col, (maxLength + 2) * 256); + } + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + workbook.write(out); + return out.toByteArray(); + + } catch (IOException e) { + throw new RuntimeException("엑셀 생성 실패", e); + } + } + + private static boolean isNumeric(String value) { + if (value == null) return false; + try { + Double.parseDouble(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + private static int getByteLength(String value) { + return value == null ? 0 : value.getBytes().length; + } + + private static CellStyle createHeaderStyle(Workbook workbook, IndexedColors bgColor) { + CellStyle style = workbook.createCellStyle(); + Font font = workbook.createFont(); + font.setBold(true); + style.setFont(font); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFillForegroundColor(bgColor.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + setBorder(style); + return style; + } + + private static CellStyle createBodyStyle(Workbook workbook) { + CellStyle style = workbook.createCellStyle(); + style.setAlignment(HorizontalAlignment.LEFT); + style.setVerticalAlignment(VerticalAlignment.CENTER); + setBorder(style); + return style; + } + + private static CellStyle createCommaStyle(Workbook workbook) { + CellStyle style = workbook.createCellStyle(); + style.setAlignment(HorizontalAlignment.RIGHT); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setDataFormat(workbook.createDataFormat().getFormat("#,##0")); + setBorder(style); + return style; + } + + private static void setBorder(CellStyle style) { + style.setBorderTop(BorderStyle.THIN); + style.setBorderBottom(BorderStyle.THIN); + style.setBorderLeft(BorderStyle.THIN); + style.setBorderRight(BorderStyle.THIN); + } +} diff --git a/admin/src/main/java/app/module/admin/config/application/util/model/ExcelSheetDto.java b/admin/src/main/java/app/module/admin/config/application/util/model/ExcelSheetDto.java new file mode 100644 index 00000000..176d6ba7 --- /dev/null +++ b/admin/src/main/java/app/module/admin/config/application/util/model/ExcelSheetDto.java @@ -0,0 +1,45 @@ +package app.module.admin.config.application.util.model; + +import org.apache.poi.ss.usermodel.IndexedColors; +import java.util.List; +import java.util.Set; + +import java.util.Map; + +public class ExcelSheetDto { + /** + * 시트명 + */ + private String sheetName; + /** + * 테이블 해더 리스트 + */ + private List headers; + /** + * 데이터 리스트 (해더와 같아야 한다. 값이 없다면 null이라도 넣어줘야해요.) + */ + private List> data; + /** + * 입력한 데이터 중 comma가 필요한 라인 선택 0 부터 + */ + private Set commaColumns; + /** + * 해더의 배경색 지정 : 0부터 시작 + */ + private Map headerBgColors; // 💡 추가: 컬럼별 배경색 + + public ExcelSheetDto(String sheetName, List headers, List> data, + Set commaColumns, Map headerBgColors) { + this.sheetName = sheetName; + this.headers = headers; + this.data = data; + this.commaColumns = commaColumns; + this.headerBgColors = headerBgColors; + } + + public String getSheetName() { return sheetName; } + public List getHeaders() { return headers; } + public List> getData() { return data; } + public Set getCommaColumns() { return commaColumns; } + public Map getHeaderBgColors() { return headerBgColors; } +} diff --git a/admin/src/main/java/app/module/admin/usecase/excel/getExcelMultilSheet/adapters/web/GetExcelMultiSheetController.java b/admin/src/main/java/app/module/admin/usecase/excel/getExcelMultilSheet/adapters/web/GetExcelMultiSheetController.java new file mode 100644 index 00000000..9f909e84 --- /dev/null +++ b/admin/src/main/java/app/module/admin/usecase/excel/getExcelMultilSheet/adapters/web/GetExcelMultiSheetController.java @@ -0,0 +1,124 @@ +package app.module.admin.usecase.excel.getExcelMultilSheet.adapters.web; + +import app.module.admin.config.application.util.model.ExcelSheetDto; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import app.module.admin.config.application.util.ExcelWriterUtil; +import java.util.List; +import java.util.Set; +import org.apache.poi.ss.usermodel.IndexedColors; +import java.util.Map; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +@RestController +@RequiredArgsConstructor +class GetExcelMultiSheetController { + + @GetMapping("/api/admin/excel/multisheet") + public ResponseEntity exportHouseholdExcel() { + + // 시트 1: 조사 대상 목록 (타이틀 10개) + ExcelSheetDto sheet1 = new ExcelSheetDto( + "조사 대상", + List.of("ID", "이름", "성별", "나이", "주소", "전화번호", "이메일", "등록일", "상태", "비고"), + List.of( + List.of("1", "홍길동", "남", "30", "서울", "010-1234-5678", "hong@example.com", "2024-01-01", "완료", ""), + List.of("2", "김영희", "여", "28", "부산", "010-2222-3333", "kim@example.com", "2024-01-02", "미완료", "응답 거부") + ), + Set.of(3), // 나이 컬럼에 콤마 포맷 적용 (예시용) + Map.of( + 0, IndexedColors.LIGHT_CORNFLOWER_BLUE, + 3, IndexedColors.LIGHT_YELLOW, + 7, IndexedColors.LIGHT_ORANGE + ) + ); + + /* + + 취득 데이터는 변환해서 넣어줘도 됩니다. + List rawList = ... // List를 캐스팅 or 변환 + List> excelData = rawList.stream() + .map(dto -> List.of( + String.valueOf(dto.getId()), + dto.getName(), + dto.getGender(), + String.valueOf(dto.getAge()), + dto.getAddress(), + dto.getPhone(), + dto.getEmail(), + dto.getRegDate().toString(), + dto.getStatus(), + dto.getNote() + )) + .toList(); + + + ExcelSheetDto sheet = new ExcelSheetDto( + "조사 대상", + List.of("ID", "이름", "성별", "나이", "주소", "전화번호", "이메일", "등록일", "상태", "비고"), + excelData, // <----------------------------------@@@@@@@@@@@@@@@@ + Set.of(3), + Map.of( + 0, IndexedColors.LIGHT_CORNFLOWER_BLUE, + 3, IndexedColors.LIGHT_YELLOW, + 7, IndexedColors.LIGHT_ORANGE + ) + ); + */ + + // 시트 2: 응답 통계 (타이틀 7개) + ExcelSheetDto sheet2 = new ExcelSheetDto( + "응답 통계", + List.of("구분", "총건수", "응답수", "미응답", "응답률", "평균시간", "비고"), + List.of( + List.of("전체", "1000", "850", "150", "85%", "5분", ""), + List.of("서울", "400", "360", "40", "90%", "4분", "") + ), + Set.of(1, 2, 3), // 숫자열에 콤마 포맷 적용 + Map.of( + 1, IndexedColors.LIGHT_GREEN, + 2, IndexedColors.LIGHT_GREEN, + 3, IndexedColors.LIGHT_YELLOW + ) + ); + + // 시트 3: 조사자별 실적 (타이틀 5개) + ExcelSheetDto sheet3 = new ExcelSheetDto( + "조사자 실적", + List.of("조사자명", "조사건수", "완료건수", "진행률", "비고"), + List.of( + List.of("박조사", "200", "180", "90%", ""), + List.of("이조사", "150", "100", "66.6%", "") + ), + Set.of(1, 2), // 조사건수, 완료건수에 콤마 포맷 + Map.of( + 0, IndexedColors.LIGHT_TURQUOISE, + 1, IndexedColors.LIGHT_ORANGE, + 2, IndexedColors.LIGHT_ORANGE + ) + ); + + // 시트 모음 + List sheets = List.of(sheet1, sheet2, sheet3); + + byte[] excel = ExcelWriterUtil.writeExcel(sheets); + + + String rawFileName = "조사결과_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + ".xlsx"; + String encodedFileName = URLEncoder.encode(rawFileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); + + return ResponseEntity.ok() + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName) + .body(excel); + } +} \ No newline at end of file