복's

Apache POI 라이브러리 엑셀 다운로드 본문

프레임워크/Spring

Apache POI 라이브러리 엑셀 다운로드

나복이 2024. 7. 19. 23:45
728x90

📌 의존성 추가

먼저 엑셀 라이브러리 Apache POI 의존성 추가를 해주었다.

implementation group: 'org.apache.poi', name: 'poi', version: '5.2.3'

📌 엑셀 파일 다운로드

Docs 에 전부 나와있기 때문에 따로 검색할 필요 없이 쭉 훑으면서 하나씩 진행할 예정이다.

뭐... 말해 뭐하나 바로 엑셀 파일부터 만들어보자.

public void downloadBasicExcelFile() throws IOException {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet1 = wb.createSheet("Hello World!!!");

    try(OutputStream fileOut = new FileOutputStream("book.xls")) {
        wb.write(fileOut);
    } catch (Exception e) {

    } finally {
        wb.close();
    }
}

특별할 것 없이 시트 생성 후 이름 설정하고 엑셀 파일 생성 해주는 코드이다.

시트를 생성할 때는 아래와 같은 규칙을 Docs 에서 확인할 수 있고

// Note that sheet name is Excel must not exceed 31 characters
// and must not contain any of the any of the following characters:
// 0x0000
// 0x0003
// colon (:)
// backslash (\)
// asterisk (*)
// question mark (?)
// forward slash (/)
// opening square bracket ([)
// closing square bracket (])

라이브러리의 인터페이스 내부에 상수로도 최대 글자 관해서는 확인할 수 있다.

int MAX_SENSITIVE_SHEET_NAME_LEN = 31;

[ Hello World 엑셀 ]

Docs 만 따라서 코드 몇 줄 타이핑 하니까 엑셀 파일이 뚝딱 하고 만들어졌다.


📌 엑셀 파일 다운로드

그러면 이제는 DB 에서 데이터를 받아서 엑셀 파일을 다운로드 해보자

이전에 스크래핑하면서 DB 에 저장한 책 데이터 카테고리는 총 3개 MYSTERY, TRAVEL, HISTORICAL_FICTION 이다.

 

목표는 Sheet 별로 나눠서, 카테고리별로 나눠서 다운로드 할 것!!! 입니다.

먼저 DB 에서 데이터를 확인해 보겠습니다.

[ SELECT * FROM book; ]

데이터는 확인 했습니다.

public void downloadAllBooksExcelFile() throws IOException {
        Map<BookCategory, List<Book>> books = bookRepository.findAll()
                                                            .stream()
                                                            .collect(Collectors.groupingBy(Book::getCategory));
        Workbook wb = new HSSFWorkbook();
        Map<BookCategory, Sheet> sheetMap = getBookCategorySheetMap(wb);

        for(BookCategory key : books.keySet()) {
            Sheet sheet = sheetMap.get(key);
            List<Book> bookForCategory = books.get(key);

            for(int idx = 0; idx < bookForCategory.size(); idx++) {
                Row row = sheet.createRow(idx);

                row.createCell(0).setCellValue(bookForCategory.get(idx).getId());
                row.createCell(1).setCellValue(bookForCategory.get(idx).getTitle());
                row.createCell(2).setCellValue(bookForCategory.get(idx).getStars().name());
                row.createCell(3).setCellValue(bookForCategory.get(idx).getPrice());
                row.createCell(4).setCellValue(bookForCategory.get(idx).getTax());
                row.createCell(5).setCellValue(bookForCategory.get(idx).getReviews());
            }
        }

        try(OutputStream fileOut = new FileOutputStream("book.xls")) {
            wb.write(fileOut);
        } catch (Exception e) {

        } finally {
            wb.close();
        }
    }

    private static Map<BookCategory, Sheet> getBookCategorySheetMap(Workbook wb) {
        Map<BookCategory, Sheet> sheetMap = new HashMap<>();

        for(BookCategory category : BookCategory.values()) {
            sheetMap.put(category, wb.createSheet(category.name()));
        }

        return sheetMap;
    }

최대한 목표에 부합하도록 코드를 작성 했습니다.

  1. 카테고리별로 Sheet 를 분리하기
    • getBookCategorySheetMap 메소드를 통해서 수행 되도록 했습니다.
  2. Grouping
    • 모든 데이터를 조회해서 Java 에서 카테고리별로 나눴습니다.
      • 데이터가 많지 않았음
      • 카테고리로 인덱스를 생성하지 않았음
  3. 엑셀 다운로드
    • Docs 에 나온대로 Sheet, Row, Cell 을 생성하고 데이터를 세팅 했습니다.

[ 엑셀 다운로드 ]

기획을 가지고 구현한게 아니기 때문에 css 라던지 데이터 타입, 포맷을 신경쓰지 않았지만 Docs 에 모든 정보가 다 나와 있으니 확인 해보면 좋을 것 같습니다.


📌 Reference

https://poi.apache.org/components/spreadsheet/quick-guide.html

 

Busy Developers' Guide to HSSF and XSSF Features

Busy Developers' Guide to HSSF and XSSF Features Busy Developers' Guide to Features Want to use HSSF and XSSF read and write spreadsheets in a hurry? This guide is for you. If you're after more in-depth coverage of the HSSF and XSSF user-APIs, please consu

poi.apache.org

728x90