까잉이의 개발노트

java 리스트 엑셀로 다운받기 본문

개발이슈

java 리스트 엑셀로 다운받기

까잉이 2022. 8. 5. 13:13

관리자 댓글 리스트에서 버튼을 눌렀을 때

모든 댓글을 엑셀로 다운받을 수 있게끔 만들어 달라는 요청이 왔다.

아래와 같이 하면 간단하게 처리가 가능하다.

 

1. controller에서 commentService를 통해 모든 댓글 리스트를 가져온다

2. res.setContentType("application/vnd.ms-excel")으로 엑셀 파일이라는걸 명시한다

3. res.addHeader("Content-Disposition", "attachment; filename=" + fileName)

    이 부분은 저장되는 용도인지를 설정하는거다.

참고

4. jsp 혹은 html 파일명을 리턴한다

5. jsp 혹은 html에 table를 만들고 값을 출력한다

 

controller.java

@GetMapping(value="/comment/commentList_Excel")
    public String commentList_Excel(HttpServletRequest req, HttpServletResponse res, Model model) {
    	
    	// 조회
        model.addAttribute("commentList", commentService.select());

        // 엑셀파일로 다운로드
        try {
            String fileName = URLEncoder.encode("댓글목록_" + DateLib.getToday("yyyyMMdd_HHmmss") + ".xls", "UTF-8");
            res.setContentType("application/vnd.ms-excel");
            res.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        } catch (Exception e) {
        }
        
       
        return "/board/commentList_Excel";
    }

 

 

commentList_Excel.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="/WEB-INF/jsp/inc/taglib.jsp" %>
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>
    <table border="1">
        <thead>
            <tr style="background-color:#e1e1e1">
                <th>게시글번호</th>
            	<th>댓글번호</th>
                <th>댓글내용</th>
                <th>작성자</th>
                <th>작성일</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach var="comment" items="${commentList}" varStatus="i">
                <tr>
                    <td>${comment.board_seq}</td>
                    <td>${comment.comment_seq}</td>
                    <td>${comment.comment}</td>
                    <td>${comment.nick_name}</td>
                    <td>${comment.cre_dt}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</body>
</html>

 

결과

 

잘 다운받아지고 출력도 잘 되어 나온다👍

Comments