programming language/Java

Java _ 데이터를 엑셀 파일로 만들기

Lcoding 2024. 11. 19. 11:32
반응형

안녕하세요,

오늘은 지난번 복수개의 엑셀 파일을 병합하기에서 안다고 가정하였던 데이터를 하나의 엑셀파일로 떨구는 메서드 생성에 대하여 알아보겠습니다.

 

1. Apache POI 라이브러리가 필요하며, Maven에서 의존성을 추가해야 합니다

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>

 

2. DataList와 FilePath를 파라미터로 받는 Excel생성

2-1. 첫번째는 Excel생성 메서드입니다.

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelUtil {

    /**
     * 데이터를 받아 Excel 파일로 저장하는 메서드.
     *
     * @param data      Excel에 작성할 2차원 리스트 데이터
     * @param filePath  저장될 파일 경로
     * @return 저장 성공 여부
     */
    public static boolean toExcelFile(List<List<Object>> data, String filePath) {
        // Excel Workbook 생성
        try (Workbook workbook = new XSSFWorkbook()) {
            // 기본 시트 생성
            Sheet sheet = workbook.createSheet("Sheet1");

            // 데이터 작성
            for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
                Row row = sheet.createRow(rowIndex);
                List<Object> rowData = data.get(rowIndex);

                for (int colIndex = 0; colIndex < rowData.size(); colIndex++) {
                    Cell cell = row.createCell(colIndex);
                    Object value = rowData.get(colIndex);

                    // 값에 따라 셀에 데이터 삽입
                    if (value instanceof String) {
                        cell.setCellValue((String) value);
                    } else if (value instanceof Number) {
                        cell.setCellValue(((Number) value).doubleValue());
                    } else if (value instanceof Boolean) {
                        cell.setCellValue((Boolean) value);
                    } else {
                        cell.setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            // 파일로 저장
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                workbook.write(fos);
            }

            System.out.println("Excel 파일 생성 완료: " + filePath);
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

 

2-2. 위의 메서드를 호출하는 부분입니다.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // 테스트 데이터
        List<List<Object>> data = Arrays.asList(
                Arrays.asList("ID", "Name", "Age", "Active"),
                Arrays.asList(1, "Alice", 30, true),
                Arrays.asList(2, "Bob", 24, false),
                Arrays.asList(3, "Charlie", 29, true)
        );

        // 저장 경로
        String filePath = "output.xlsx";

        // Excel 파일 생성
        boolean success = ExcelUtil.toExcelFile(data, filePath);

        if (success) {
            System.out.println("파일 생성 성공: " + filePath);
        } else {
            System.out.println("파일 생성 실패");
        }
    }
}

 

위의 메서드를 실행하였을때 결과적으로 생성되는 엑셀 파일의 예시입니다.

 

 

3. List<?> dataList, Class<?> voClass, String group, String[] headers, String fileName를 파라미터로 받는 Excel생성

3-1. 첫번째는 Excel생성 메서드입니다.

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

public class ExcelUtil {

    /**
     * 데이터를 Excel 파일로 변환하는 메서드.
     *
     * @param dataList  데이터 리스트 (VO 객체 리스트)
     * @param voClass   VO 클래스 타입
     * @param group     그룹 이름 (시트 이름이나 필터링용)
     * @param headers   Excel 헤더 정보
     * @param fileName  저장될 파일 이름 (경로 포함)
     * @return 저장 성공 여부
     */
    public static boolean toExcelFile(List<?> dataList, Class<?> voClass, String group, String[] headers, String fileName) {
        // Workbook 생성
        try (Workbook workbook = new XSSFWorkbook()) {
            // 그룹 이름을 시트 이름으로 사용
            Sheet sheet = workbook.createSheet(group != null ? group : "Sheet1");

            // 헤더 작성
            Row headerRow = sheet.createRow(0);
            for (int colIndex = 0; colIndex < headers.length; colIndex++) {
                Cell cell = headerRow.createCell(colIndex);
                cell.setCellValue(headers[colIndex]);

                // 스타일 설정 (선택 사항)
                CellStyle style = workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
            }

            // 데이터 작성
            for (int rowIndex = 0; rowIndex < dataList.size(); rowIndex++) {
                Object data = dataList.get(rowIndex);
                Row row = sheet.createRow(rowIndex + 1);

                for (int colIndex = 0; colIndex < headers.length; colIndex++) {
                    Cell cell = row.createCell(colIndex);
                    try {
                        // VO 클래스의 필드에서 값 추출
                        Field field = voClass.getDeclaredField(headers[colIndex]);
                        field.setAccessible(true);
                        Object value = field.get(data);

                        // 데이터 타입에 따라 값 설정
                        if (value instanceof String) {
                            cell.setCellValue((String) value);
                        } else if (value instanceof Number) {
                            cell.setCellValue(((Number) value).doubleValue());
                        } else if (value instanceof Boolean) {
                            cell.setCellValue((Boolean) value);
                        } else {
                            cell.setCellValue(value != null ? value.toString() : "");
                        }

                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                        cell.setCellValue("ERROR");
                    }
                }
            }

            // 파일 저장
            try (FileOutputStream fos = new FileOutputStream(fileName)) {
                workbook.write(fos);
            }

            System.out.println("Excel 파일 생성 완료: " + fileName);
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

 

3-2. 위의 메서드에서 사용하는 Vo입니다.

public class User {
    private String id;
    private String name;
    private int age;

    // 생성자 및 Getter/Setter
    public User(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

3-3. 위의 메서드를 호출하는 부분입니다.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // 데이터 준비
        List<User> userList = Arrays.asList(
                new User("U001", "Alice", 30),
                new User("U002", "Bob", 25),
                new User("U003", "Charlie", 28)
        );

        // 헤더 정의 (VO 필드명과 일치해야 함)
        String[] headers = {"id", "name", "age"};

        // 그룹 및 파일 이름
        String group = "UserGroup";
        String fileName = "users.xlsx";

        // Excel 파일 생성
        boolean result = ExcelUtil.toExcelFile(userList, User.class, group, headers, fileName);

        if (result) {
            System.out.println("Excel 파일 생성 성공: " + fileName);
        } else {
            System.out.println("Excel 파일 생성 실패");
        }
    }
}

 

위의 메서드를 실행하였을때 결과적으로 생성되는 엑셀 파일의 예시입니다.

 

 

이상 자바에서 데이터로 엑셀 만드는 방법에 대한 글이었습니다.

 

감사합니다.

 

 

 

 

 

반응형