Spring(스프링), Spring Boot(스프링부트), JSP

Spring + jsp excel 추출하기 excel export, table 내용을 excel로 다운로드

알통몬_ 2018. 9. 12. 15:14
반응형


공감 및 댓글은 포스팅 하는데

 아주아주 큰 힘이 됩니다!!

포스팅 내용이 찾아주신 분들께 

도움이 되길 바라며

더 깔끔하고 좋은 포스팅을 

만들어 나가겠습니다^^

 


이번 포스팅에서는 jsp에서 excel을 추출하는 방법에 대해서 알아보겠습니다.


기본적으로

<table>

...

</table> 을 excel로 추출하는 방식이기 때문에

css를 적용시켜 놓으면 그 속서들까지 excel에 적용됩니다.

그리고 추출된 excel 파일은 excel viewer, 카톡이나 naver office에서는 열리지 않고,

microsoft excel에서 경고메시지를 무시해야 열어볼 수 있습니다.


저는 저장된 온도를 가져오는 table을 excel로 추출해봤습니다.

excel파일을 추출할 exportToExcel.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<%@ page language="java"
    contentType="application/vnd.ms-excel; charset=UTF-8"
    pageEncoding="EUC-KR" import="java.util.*"%>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%
    SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd", Locale.KOREA);
    String today = format.format(new Date());
    String days = request.getParameter("days");
    String fileName = today + "." + days;
      response.setHeader("Content-Type""application/vnd.ms-xls");
    response.setHeader("Content-Disposition",
            "attachment; filename=" + new String((fileName).getBytes("KSC5601"), "8859_1"+ ".xls");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ko" style="overflow: hidden">
<head>
<meta http-equiv="content-type" content="text/html; utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>엑셀 다운로드</title>
<style>
.table-wrapper-scroll-y {
    display: block;
    max-height: 700px;
    overflow-y: auto;
    -ms-overflow-style: -ms-autohiding-scrollbar;
}
</style>
</head>
<body>
    <table style="background: #ffffff">
        <thead>
            <tr>
                <th>${nickname}</th>
                <th>시간</th>
                <th>아침6시(ºC)</th>
                <th>최고(ºC)</th>
                <th>최저(ºC)</th>
                <th>평균(ºC)</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${data1}" varStatus="status">
                <tr>
                    <td></td>
                    <td>${data1[status.index].time.substring(0, 10)}</td>
                    <td>${data1[status.index].data}</td>
                    <td>${data2[status.index].min}</td>
                    <td>${data2[status.index].max}</td>
                    <td>${data2[status.index].avg}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
 
</body>
</html>
 
cs

new String((fileName).getBytes("KSC5601"), "8859_1")

요 설정을 해줘야 한글이 깨지지 않습니다.


exportToExcel.jsp 를 호출하는 버튼 태그

1
2
3
4
5
6
7
<button id="exportToExcel" onclick="exportToExcel()"
    style="z-index: 1110; background: rgb(142, 31, 31); 
float: right; margin-bottom: 16px; 
margin-top: 16px; margin-right: 16px; 
display: block;"
    class="mdl-button mdl-js-button mdl-button--fab"
    data-toggle="modal" data-target="#myModal">
    <i class="material-icons">save</i>
</button>
 
cs


exportToExcel() 함수

1
2
3
4
5
6
7
<script>
    function exportToExcel() {
        console.log("click");
        location.href= "./exportToExcel?
id=${id}&nickname=${nickname}&from=${from}&to=${to}&days=${days}";
        
    }
</script>
cs


스프링 HomeController 에서 받은 값들을 처리해서 ExportToExcel.jsp 로 보냅니다.

그렇게 되면 아래처럼 table 안의 값들이 excel로 변경되어 다운로드 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<table style="background: #ffffff">
        <thead>
            <tr>
                <th>${nickname}</th>
                <th>시간</th>
                <th>아침6시(ºC)</th>
                <th>최고(ºC)</th>
                <th>최저(ºC)</th>
                <th>평균(ºC)</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${data1}" varStatus="status">
                <tr>
                    <td></td>
                    <td>${data1[status.index].time.substring(0, 10)}</td>
                    <td>${data1[status.index].data}</td>
                    <td>${data2[status.index].min}</td>
                    <td>${data2[status.index].max}</td>
                    <td>${data2[status.index].avg}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
cs


이상입니다.

해보시면 어렵지 않게 하실 수 있습니다 ㅎㅎ

반응형