Excel다운로드
This commit is contained in:
@@ -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<ExcelSheetDto> 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<String> headers = sheetDto.getHeaders();
|
||||||
|
List<List<String>> 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<String> 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<String> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String> headers;
|
||||||
|
/**
|
||||||
|
* 데이터 리스트 (해더와 같아야 한다. 값이 없다면 null이라도 넣어줘야해요.)
|
||||||
|
*/
|
||||||
|
private List<List<String>> data;
|
||||||
|
/**
|
||||||
|
* 입력한 데이터 중 comma가 필요한 라인 선택 0 부터
|
||||||
|
*/
|
||||||
|
private Set<Integer> commaColumns;
|
||||||
|
/**
|
||||||
|
* 해더의 배경색 지정 : 0부터 시작
|
||||||
|
*/
|
||||||
|
private Map<Integer, IndexedColors> headerBgColors; // 💡 추가: 컬럼별 배경색
|
||||||
|
|
||||||
|
public ExcelSheetDto(String sheetName, List<String> headers, List<List<String>> data,
|
||||||
|
Set<Integer> commaColumns, Map<Integer, IndexedColors> headerBgColors) {
|
||||||
|
this.sheetName = sheetName;
|
||||||
|
this.headers = headers;
|
||||||
|
this.data = data;
|
||||||
|
this.commaColumns = commaColumns;
|
||||||
|
this.headerBgColors = headerBgColors;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSheetName() { return sheetName; }
|
||||||
|
public List<String> getHeaders() { return headers; }
|
||||||
|
public List<List<String>> getData() { return data; }
|
||||||
|
public Set<Integer> getCommaColumns() { return commaColumns; }
|
||||||
|
public Map<Integer, IndexedColors> getHeaderBgColors() { return headerBgColors; }
|
||||||
|
}
|
||||||
@@ -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<byte[]> 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<Household> rawList = ... // List<Object>를 캐스팅 or 변환
|
||||||
|
List<List<String>> 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<ExcelSheetDto> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user