260309_01_ENH: 엑셀 매퍼에 HeaderRow 지정 기능 추가

This commit is contained in:
2026-03-09 16:24:02 +09:00
parent cca5a9b5be
commit 03a368b120
2 changed files with 163 additions and 81 deletions

View File

@@ -4,7 +4,7 @@ plugins {
}
//버전 변경은 여기서
def commonVer = "beta.1.0.66"
def commonVer = "beta.1.0.67"
group = 'com.kri.common'
version = commonVer

View File

@@ -48,6 +48,12 @@ public final class ExcelMapper {
* ========================================================= */
public static <T> Workbook writeToWorkbook(List<T> data, Class<T> clazz) {
return writeToWorkbook(data, clazz, 1);
}
public static <T> Workbook writeToWorkbook(List<T> data, Class<T> clazz, int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
@@ -55,14 +61,15 @@ public final class ExcelMapper {
List<ExcelFieldMeta> fields = getExcelFields(clazz);
// 2) 헤더 작성
Row headerRow = sheet.createRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.createRow(headerRowNum);
for (ExcelFieldMeta meta : fields) {
Cell cell = headerRow.createCell(meta.order());
cell.setCellValue(meta.header());
}
// 3) 데이터 작성
int rowIndex = 1;
int rowIndex = headerRowNum + 1;
if (data != null) {
for (T item : data) {
Row row = sheet.createRow(rowIndex++);
@@ -91,10 +98,17 @@ public final class ExcelMapper {
* ========================================================= */
public static <T> List<T> readFromWorkbook(Workbook workbook, Class<T> clazz) {
return readFromWorkbook(workbook, clazz, 1);
}
public static <T> List<T> readFromWorkbook(Workbook workbook, Class<T> clazz, int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
Sheet sheet = workbook.getSheetAt(0);
// 1) 헤더 행
Row headerRow = sheet.getRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.getRow(headerRowNum);
if (headerRow == null) {
return List.of();
}
@@ -104,8 +118,10 @@ public final class ExcelMapper {
for (int c = 0; c < lastCellNum; c++) {
Cell cell = headerRow.getCell(c);
if (cell != null) {
String headerName = cell.getStringCellValue();
headerIndexMap.put(headerName, c);
String headerName = ExcelUtil.getStringCell(cell);
if (headerName != null) {
headerIndexMap.put(headerName, c);
}
}
}
@@ -116,7 +132,7 @@ public final class ExcelMapper {
List<T> result = new ArrayList<>();
int lastRowNum = sheet.getLastRowNum();
for (int r = 1; r <= lastRowNum; r++) {
for (int r = headerRowNum + 1; r <= lastRowNum; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
@@ -153,9 +169,16 @@ public final class ExcelMapper {
* ========================================================= */
public static List<Map<String, String>> readAsMapList(Workbook workbook) {
return readAsMapList(workbook, 1);
}
public static List<Map<String, String>> readAsMapList(Workbook workbook, int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
Sheet sheet = workbook.getSheetAt(0);
Row headerRow = sheet.getRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.getRow(headerRowNum);
if (headerRow == null) {
return List.of();
}
@@ -165,14 +188,17 @@ public final class ExcelMapper {
for (int c = 0; c < lastCol; c++) {
Cell cell = headerRow.getCell(c);
String headerName = (cell != null) ? cell.getStringCellValue() : ("COL_" + c);
String headerName = ExcelUtil.getStringCell(cell);
if (headerName == null || headerName.isBlank()) {
headerName = "COL_" + c;
}
headers.add(headerName);
}
List<Map<String, String>> result = new ArrayList<>();
int lastRow = sheet.getLastRowNum();
for (int r = 1; r <= lastRow; r++) {
for (int r = headerRowNum + 1; r <= lastRow; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
@@ -203,6 +229,12 @@ public final class ExcelMapper {
* ========================================================= */
public static Workbook writeFromMapList(List<? extends Map<String, ?>> rows) {
return writeFromMapList(rows, 1);
}
public static Workbook writeFromMapList(List<? extends Map<String, ?>> rows, int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
@@ -221,14 +253,15 @@ public final class ExcelMapper {
List<String> headers = new ArrayList<>(headerSet);
// 헤더
Row headerRow = sheet.createRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.createRow(headerRowNum);
for (int c = 0; c < headers.size(); c++) {
Cell cell = headerRow.createCell(c);
cell.setCellValue(headers.get(c));
}
// 데이터
int rowIndex = 1;
int rowIndex = headerRowNum + 1;
for (Map<String, ?> rowMap : rows) {
Row row = sheet.createRow(rowIndex++);
if (rowMap == null) {
@@ -266,6 +299,15 @@ public final class ExcelMapper {
public static <T> SXSSFWorkbook writeStreaming(List<T> data,
Class<T> clazz,
int rowAccessWindowSize) {
return writeStreaming(data, clazz, rowAccessWindowSize, 1);
}
public static <T> SXSSFWorkbook writeStreaming(List<T> data,
Class<T> clazz,
int rowAccessWindowSize,
int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
Sheet sheet = workbook.createSheet("Sheet1");
@@ -273,14 +315,15 @@ public final class ExcelMapper {
List<ExcelFieldMeta> fields = getExcelFields(clazz);
// 2) 헤더
Row headerRow = sheet.createRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.createRow(headerRowNum);
for (ExcelFieldMeta meta : fields) {
Cell cell = headerRow.createCell(meta.order());
cell.setCellValue(meta.header());
}
// 3) 데이터
int rowIndex = 1;
int rowIndex = headerRowNum + 1;
if (data != null) {
for (T item : data) {
Row row = sheet.createRow(rowIndex++);
@@ -297,11 +340,6 @@ public final class ExcelMapper {
}
}
// autoSizeColumn은 대용량에서는 비추천 (메모리 많이 씀) -> 필요하면 호출
// for (ExcelFieldMeta meta : fields) {
// sheet.autoSizeColumn(meta.order());
// }
return workbook;
}
@@ -312,6 +350,14 @@ public final class ExcelMapper {
public static <T> StreamingWriter<T> openStreamingWriter(Class<T> clazz,
int rowAccessWindowSize) {
return openStreamingWriter(clazz, rowAccessWindowSize, 1);
}
public static <T> StreamingWriter<T> openStreamingWriter(Class<T> clazz,
int rowAccessWindowSize,
int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
Sheet sheet = workbook.createSheet("Sheet1");
@@ -322,17 +368,26 @@ public final class ExcelMapper {
List<ExcelFieldMeta> fields = getExcelFields(clazz);
// 2) 헤더 작성
Row headerRow = sheet.createRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.createRow(headerRowNum);
for (ExcelFieldMeta meta : fields) {
Cell cell = headerRow.createCell(meta.order());
cell.setCellValue(meta.header());
}
return new StreamingWriter<>(workbook, sheet, fields, 1);
return new StreamingWriter<>(workbook, sheet, fields, headerRowNum + 1);
}
public static SXSSFWorkbook writeStreamingFromMap(List<? extends Map<String, ?>> rows,
int rowAccessWindowSize) {
return writeStreamingFromMap(rows, rowAccessWindowSize, 1);
}
public static SXSSFWorkbook writeStreamingFromMap(List<? extends Map<String, ?>> rows,
int rowAccessWindowSize,
int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
SXSSFWorkbook workbook = new SXSSFWorkbook(rowAccessWindowSize);
Sheet sheet = workbook.createSheet("Sheet1");
@@ -350,13 +405,14 @@ public final class ExcelMapper {
List<String> headers = new ArrayList<>(headerSet);
// 헤더
Row headerRow = sheet.createRow(0);
int headerRowNum = toPoiRowIndex(headerRowIndex);
Row headerRow = sheet.createRow(headerRowNum);
for (int c = 0; c < headers.size(); c++) {
headerRow.createCell(c).setCellValue(headers.get(c));
}
// 데이터
int rowIndex = 1;
int rowIndex = headerRowNum + 1;
for (Map<String, ?> rowMap : rows) {
Row row = sheet.createRow(rowIndex++);
if (rowMap == null) {
@@ -377,20 +433,31 @@ public final class ExcelMapper {
/* =========================================================
* 6. Streaming Write (SXSSFWorkbook) - Map 기반
* 6. Streaming Read (XSSFReader + SAX) -> RowMapHandler
* ========================================================= */
/**
* XSSFReader + SAX 기반 스트리밍 읽기. - 첫 번째 시트만 읽음. - 1행은 헤더, 2행부터 데이터로 가정.
* XSSFReader + SAX 기반 스트리밍 읽기.
* - 첫 번째 시트만 읽음.
* - headerRowIndex 행을 헤더로 간주하고, 그 다음 행부터 데이터를 읽음.
*/
public static void readStreaming(InputStream inputStream, RowMapHandler handler) {
try {
OPCPackage pkg = OPCPackage.open(inputStream);
readStreaming(inputStream, 1, handler);
}
public static void readStreaming(
InputStream inputStream,
int headerRowIndex,
RowMapHandler handler
) {
validateHeaderRowIndex(headerRowIndex);
try (OPCPackage pkg = OPCPackage.open(inputStream)) {
XSSFReader reader = new XSSFReader(pkg);
SharedStringsTable sst = (SharedStringsTable) reader.getSharedStringsTable();
XMLReader parser = XMLReaderFactory.createXMLReader();
SheetToMapHandler sheetHandler = new SheetToMapHandler(sst, handler);
SheetToMapHandler sheetHandler = new SheetToMapHandler(sst, handler, headerRowIndex);
parser.setContentHandler(sheetHandler);
Iterator<InputStream> sheets = reader.getSheetsData();
@@ -400,17 +467,11 @@ public final class ExcelMapper {
parser.parse(sheetSource);
}
}
pkg.close();
} catch (Exception e) {
throw new RuntimeException("Streaming 엑셀 읽기 중 오류", e);
}
}
/* =========================================================
* 7. Streaming Read (XSSFReader + SAX) -> RowMapHandler
* ========================================================= */
private static List<ExcelFieldMeta> getExcelFields(Class<?> clazz) {
List<ExcelFieldMeta> result = new ArrayList<>();
@@ -458,15 +519,12 @@ public final class ExcelMapper {
field.set(target, Long.parseLong(trimmed));
} else if (type == Boolean.class || type == boolean.class) {
// "true"/"false" 외에 "Y"/"N" 같은 것도 처리하고 싶으면 여기서 추가 가능
field.set(target, Boolean.parseBoolean(trimmed));
} else {
// TODO: 필요 시 LocalDate, BigDecimal 등 타입 확장
field.set(target, trimmed);
}
} catch (NumberFormatException e) {
// 어디서 어떤 값 때문에 깨졌는지 로그/예외에 남겨두면 디버깅 편함
throw new RuntimeException(
"엑셀 값 파싱 실패: field=" + field.getName() +
", type=" + type.getSimpleName() +
@@ -476,20 +534,26 @@ public final class ExcelMapper {
}
}
private static void validateHeaderRowIndex(int headerRowIndex) {
if (headerRowIndex < 1) {
throw new IllegalArgumentException("headerRowIndex는 1 이상이어야 합니다.");
}
}
private static int toPoiRowIndex(int headerRowIndex) {
return headerRowIndex - 1;
}
@FunctionalInterface
public interface RowMapHandler {
/**
* @param row 헤더명 -> 값 맵 (1행은 헤더라서 콜백 X, 2행부터 데이터)
* @param row 헤더명 -> 값 맵 (headerRowIndex 다음 행부터 데이터)
* @param rowIndex 엑셀 실제 행 번호 (1-based)
*/
void handleRow(Map<String, String> row, int rowIndex);
}
/* =========================================================
* 8. 내부 메타 수집 & 필드 세터
* ========================================================= */
/**
* chunk 단위로 append 가능한 SXSSF Writer - rowAccessWindowSize 만큼만 메모리에 유지하고 나머지는 temp file로 flush -
* 마지막에 writeTo(OutputStream) 한 번 호출로 XLSX 완성
@@ -545,31 +609,32 @@ public final class ExcelMapper {
@Override
public void close() throws IOException {
// SXSSF temp 파일 제거
workbook.dispose();
workbook.close();
}
}
/**
* SAX 핸들러: 한 행을 Map<String,String> 으로 만들어 RowMapHandler에 전달.
* SAX 핸들러: 지정한 헤더 행을 기준으로 한 행을 Map<String,String> 으로 만들어 RowMapHandler에 전달.
*/
private static class SheetToMapHandler extends DefaultHandler {
private final SharedStringsTable sst;
private final RowMapHandler handler;
private final int headerRowIndex; // 1-based
private final Map<Integer, String> cellMap = new HashMap<>();
private int currentRowNum;
private String currentCellRef;
private String currentCellType;
private StringBuilder currentValue;
private boolean isValueOpen;
private List<String> headers = new ArrayList<>();
private boolean headerProcessed = false;
SheetToMapHandler(SharedStringsTable sst, RowMapHandler handler) {
SheetToMapHandler(SharedStringsTable sst, RowMapHandler handler, int headerRowIndex) {
validateHeaderRowIndex(headerRowIndex);
this.sst = sst;
this.handler = handler;
this.headerRowIndex = headerRowIndex;
}
@Override
@@ -584,7 +649,7 @@ public final class ExcelMapper {
cellMap.clear();
} else if ("c".equals(qName)) {
currentCellRef = attributes.getValue("r");
currentCellType = attributes.getValue("t"); // "s"면 shared string
currentCellType = attributes.getValue("t");
} else if ("v".equals(qName) || "t".equals(qName)) {
currentValue = new StringBuilder();
isValueOpen = true;
@@ -611,38 +676,55 @@ public final class ExcelMapper {
isValueOpen = false;
currentValue = null;
} else if ("row".equals(qName)) {
// 1행: 헤더
if (!headerProcessed) {
if (!cellMap.isEmpty()) {
int maxCol = cellMap.keySet().stream().max(Integer::compareTo).orElse(-1);
headers = new ArrayList<>(maxCol + 1);
for (int c = 0; c <= maxCol; c++) {
String header = cellMap.getOrDefault(c, "COL_" + c);
headers.add(header);
}
}
headerProcessed = true;
} else {
if (headers == null || headers.isEmpty()) {
return;
}
return;
}
Map<String, String> rowMap = new LinkedHashMap<>();
boolean allBlank = true;
for (int c = 0; c < headers.size(); c++) {
String v = cellMap.get(c);
if (v != null && !v.isBlank()) {
allBlank = false;
}
rowMap.put(headers.get(c), v);
}
if (!allBlank) {
handler.handleRow(rowMap, currentRowNum);
}
if ("row".equals(qName)) {
if (currentRowNum < headerRowIndex) {
return;
}
if (currentRowNum == headerRowIndex) {
buildHeaders();
return;
}
if (headers.isEmpty()) {
return;
}
Map<String, String> rowMap = new LinkedHashMap<>();
boolean allBlank = true;
for (int c = 0; c < headers.size(); c++) {
String value = cellMap.get(c);
if (value != null && !value.isBlank()) {
allBlank = false;
}
rowMap.put(headers.get(c), value);
}
if (!allBlank) {
handler.handleRow(rowMap, currentRowNum);
}
}
}
private void buildHeaders() {
if (cellMap.isEmpty()) {
headers = new ArrayList<>();
return;
}
int maxCol = cellMap.keySet().stream().max(Integer::compareTo).orElse(-1);
headers = new ArrayList<>(maxCol + 1);
for (int c = 0; c <= maxCol; c++) {
String header = cellMap.get(c);
if (header == null || header.isBlank()) {
header = "COL_" + c;
}
headers.add(header);
}
}
@@ -650,8 +732,8 @@ public final class ExcelMapper {
if ("s".equals(cellType)) {
try {
int idx = Integer.parseInt(raw);
RichTextString rich = sst.getItemAt(idx); // 또는 getEntryAt(idx) 인 버전도 있음
return (rich != null) ? rich.getString() : "";
RichTextString rich = sst.getItemAt(idx);
return rich != null ? rich.getString() : "";
} catch (Exception e) {
return raw;
}
@@ -670,4 +752,4 @@ public final class ExcelMapper {
}
}
}
}
}