본문 바로가기
■Development■/《Web》

[Web] JSP에서 데이터를 엑셀 파일로 내보내는 방법 완벽 가이드

by 은스타 2020. 4. 8.
반응형

JSP에서 데이터를 엑셀 파일로 내보내는 방법 완벽 가이드

웹 개발을 하다 보면 사용자가 데이터를 엑셀 파일로 다운로드할 수 있게 해야 하는 경우가 많습니다. 특히 JSP 환경에서 작업하는 개발자라면 이 기능을 어떻게 구현해야 할지 고민하실 텐데요. 이 글에서는 JSP에서 데이터베이스의 정보를 엑셀 파일로 변환하고 다운로드하는 방법을 단계별로 자세히 알아보겠습니다.


목차

  1. 필요한 라이브러리 준비하기
  2. 기본 엑셀 파일 생성 방법
  3. 데이터베이스 연동하기
  4. 스타일과 셀 서식 적용하기
  5. 다운로드 기능 구현하기
  6. 자주 발생하는 문제와 해결 방법

 

#1.필요한 라이브러리 준비하기

JSP에서 엑셀 파일을 생성하려면 Apache POI 라이브러리를 사용하는 것이 가장 일반적입니다. 이 라이브러리는 Microsoft Office 형식의 문서를 생성하고 수정할 수 있는 Java API를 제공합니다.

Maven 설정 (pom.xml)

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

Gradle 설정 (build.gradle)

dependencies {
    implementation 'org.apache.poi:poi:5.2.3'
    implementation 'org.apache.poi:poi-ooxml:5.2.3'
}

 

#2. 기본 엑셀 파일 생성 방법

다음은 JSP에서 기본적인 엑셀 파일을 생성하는 코드입니다.

<%@ page language="java" contentType="application/vnd.ms-excel;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.apache.poi.ss.usermodel.*"%>
<%@ page import="org.apache.poi.xssf.usermodel.*"%>
<%@ page import="java.io.*"%>
<%
    // 응답 헤더 설정
    response.setHeader("Content-Disposition", "attachment;filename=example.xlsx");

    // 워크북 생성
    XSSFWorkbook workbook = new XSSFWorkbook();

    // 워크시트 생성
    XSSFSheet sheet = workbook.createSheet("데이터 시트");

    // 헤더 행 생성
    Row headerRow = sheet.createRow(0);

    // 헤더 셀 생성
    Cell headerCell1 = headerRow.createCell(0);
    headerCell1.setCellValue("이름");

    Cell headerCell2 = headerRow.createCell(1);
    headerCell2.setCellValue("나이");

    Cell headerCell3 = headerRow.createCell(2);
    headerCell3.setCellValue("이메일");

    // 데이터 행 생성
    Row dataRow1 = sheet.createRow(1);

    // 데이터 셀 생성
    Cell dataCell1 = dataRow1.createCell(0);
    dataCell1.setCellValue("홍길동");

    Cell dataCell2 = dataRow1.createCell(1);
    dataCell2.setCellValue(30);

    Cell dataCell3 = dataRow1.createCell(2);
    dataCell3.setCellValue("hong@example.com");

    // 워크북을 출력 스트림에 쓰기
    OutputStream out2 = response.getOutputStream();
    workbook.write(out2);

    // 자원 정리
    out2.close();
    workbook.close();

    // JSP의 기본 out 객체를 무효화하여 경고 방지
    out.clear();
    out = pageContext.pushBody();
%>

 

#3. 데이터베이스 연동하기

실제 웹 애플리케이션에서는 데이터베이스에서 가져온 데이터를 엑셀 파일로 변환해야 하는 경우가 많습니다. 다음은 JSP에서 데이터베이스 데이터를 엑셀로 내보내는 예제입니다.

<%@ page language="java" contentType="application/vnd.ms-excel;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.apache.poi.ss.usermodel.*"%>
<%@ page import="org.apache.poi.xssf.usermodel.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%
    // 데이터베이스 연결 정보
    String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";
    String dbUser = "username";
    String dbPassword = "password";

    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        // JDBC 드라이버 로드
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 데이터베이스 연결
        conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);

        // SQL 쿼리 준비
        String sql = "SELECT name, age, email FROM users";
        pstmt = conn.prepareStatement(sql);

        // 쿼리 실행
        rs = pstmt.executeQuery();

        // 엑셀 파일 이름 설정
        String fileName = "users_data.xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        // 워크북 생성
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("사용자 데이터");

        // 헤더 행 생성
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("이름");
        headerRow.createCell(1).setCellValue("나이");
        headerRow.createCell(2).setCellValue("이메일");

        // 데이터 행 추가
        int rowNum = 1;
        while(rs.next()) {
            Row dataRow = sheet.createRow(rowNum++);
            dataRow.createCell(0).setCellValue(rs.getString("name"));
            dataRow.createCell(1).setCellValue(rs.getInt("age"));
            dataRow.createCell(2).setCellValue(rs.getString("email"));
        }

        // 열 너비 자동 조정
        for(int i = 0; i < 3; i++) {
            sheet.autoSizeColumn(i);
        }

        // 엑셀 파일 생성
        OutputStream outStream = response.getOutputStream();
        workbook.write(outStream);

        // 자원 정리
        workbook.close();
        outStream.close();

        // JSP의 기본 out 객체 무효화
        out.clear();
        out = pageContext.pushBody();

    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        // 자원 해제
        if(rs != null) try { rs.close(); } catch(SQLException e) {}
        if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {}
        if(conn != null) try { conn.close(); } catch(SQLException e) {}
    }
%>

 

#4. 스타일과 셀 서식 적용하기

엑셀 파일에 스타일을 적용하면 데이터를 더 보기 좋게 표현할 수 있습니다. 다음은 스타일을 적용하는 예제입니다.

<%
    // 스타일 생성
    XSSFCellStyle headerStyle = workbook.createCellStyle();

    // 배경색 설정
    headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    // 테두리 설정
    headerStyle.setBorderTop(BorderStyle.THIN);
    headerStyle.setBorderBottom(BorderStyle.THIN);
    headerStyle.setBorderLeft(BorderStyle.THIN);
    headerStyle.setBorderRight(BorderStyle.THIN);

    // 폰트 설정
    XSSFFont headerFont = workbook.createFont();
    headerFont.setBold(true);
    headerStyle.setFont(headerFont);

    // 헤더 셀에 스타일 적용
    for(int i = 0; i < headerRow.getLastCellNum(); i++) {
        headerRow.getCell(i).setCellStyle(headerStyle);
    }

    // 데이터 셀 스타일
    XSSFCellStyle dataStyle = workbook.createCellStyle();
    dataStyle.setBorderTop(BorderStyle.THIN);
    dataStyle.setBorderBottom(BorderStyle.THIN);
    dataStyle.setBorderLeft(BorderStyle.THIN);
    dataStyle.setBorderRight(BorderStyle.THIN);

    // 데이터 행에 스타일 적용
    for(int i = 1; i <= sheet.getLastRowNum(); i++) {
        Row row = sheet.getRow(i);
        for(int j = 0; j < row.getLastCellNum(); j++) {
            row.getCell(j).setCellStyle(dataStyle);
        }
    }

    // 날짜 형식 스타일
    XSSFCellStyle dateStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));

    // 숫자 형식 스타일
    XSSFCellStyle numberStyle = workbook.createCellStyle();
    numberStyle.setDataFormat(createHelper.createDataFormat().getFormat("#,##0"));
%>

 

#5. 다운로드 기능 구현하기

사용자가 버튼을 클릭하여 엑셀 파일을 다운로드할 수 있도록 하는 HTML과 JavaScript 코드입니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>엑셀 다운로드 예제</title>
    <script>
        function downloadExcel() {
            window.location.href = 'exportExcel.jsp';
        }
    </script>
</head>
<body>
    <h2>사용자 데이터</h2>
    <table border="1">
        <tr>
            <th>이름</th>
            <th>나이</th>
            <th>이메일</th>
        </tr>
        <tr>
            <td>홍길동</td>
            <td>30</td>
            <td>hong@example.com</td>
        </tr>
        <tr>
            <td>김철수</td>
            <td>25</td>
            <td>kim@example.com</td>
        </tr>
    </table>
    <br>
    <button onclick="downloadExcel()">엑셀 파일 다운로드</button>
</body>
</html>

 

#6. 자주 발생하는 문제와 해결 방법

1. 한글 깨짐 문제

JSP에서 엑셀 파일을 생성할 때 한글이 깨지는 문제가 발생할 수 있습니다. 이를 해결하기 위한 방법은 다음과 같습니다.

<%@ page language="java" contentType="application/vnd.ms-excel;charset=UTF-8" pageEncoding="UTF-8"%>
<%
    // 한글 파일명을 위한 인코딩 처리
    String fileName = "사용자_데이터.xlsx";
    String encodedFileName = new String(fileName.getBytes("UTF-8"), "8859_1");
    response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
%>

2. 대용량 데이터 처리하기

많은 양의 데이터를 엑셀로 내보낼 때는 메모리 문제가 발생할 수 있습니다. 이를 위해 SXSSF(Streaming XML SAX Sheet) API를 사용할 수 있습니다.

<%@ page import="org.apache.poi.xssf.streaming.SXSSFWorkbook"%>
<%
    // 메모리 효율적인 워크북 생성 (메모리에 100개 행만 유지)
    SXSSFWorkbook workbook = new SXSSFWorkbook(100);

    // 이후 코드는 기존과 동일
    Sheet sheet = workbook.createSheet("데이터");
    // ...

    // 사용 후 임시 파일 정리
    workbook.dispose();
%>

3. 컨트롤러에서 처리하기

실제 프로젝트에서는 JSP에서 직접 처리하기보다 컨트롤러에서 처리하는 것이 좋습니다. 다음은 Spring MVC를 사용한 예제입니다.

@Controller
public class ExcelController {

    @GetMapping("/download/excel")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=data.xlsx");

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("데이터");

        // 데이터 추가 로직
        // ...

        // 파일 출력
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}

결론

JSP에서 데이터를 엑셀 파일로 내보내는 방법에 대해 알아보았습니다. Apache POI 라이브러리를 사용하면 다양한 형식과 스타일의 엑셀 파일을 쉽게 생성할 수 있습니다. 실제 프로젝트에서는 JSP에서 직접 처리하기보다 컨트롤러 계층에서 처리하는 것이 더 좋은 방법입니다.

효율적인 데이터 관리와 사용자 편의성을 위해 엑셀 다운로드 기능을 제공하는 것은 웹 애플리케이션에서 매우 중요한 기능입니다. 이 글이 JSP 개발자들에게 도움이 되길 바랍니다.

긴 글 읽어주셔서 감사합니다.

끝.

반응형