JSP 에서 엑셀로 출력(다운로드) IE, Chrome

북마크 추가

조회 조건을 POST방식으로 컨트롤러에 넘겨 조건에 해당하는 쿼리를 돌려 엑셀로 출력 할 것이다.

 

 

 

 

<form name="searchForm" method="POST" action="" class="">

<input .....>

.

.

.

angularJS라면

<button type="button" ng-click="exportToExcel();">엑셀출력</button>

아니면

<button type="button" onclick="exportToExcel();">엑셀출력</button>

</form>

 

위와 같이 POST로 넘길 데이터를 입력받을 폼을 만든다.

 

exportToExcel 이라는 함수를 만들어 준다.

 

$scope.exportToExcel= function(){

document.searchForm.action="/exportToExcel";
document.searchForm.method="POST"
document.searchForm.submit();​

}

 

or

 

function exportToExcel(){

document.searchForm.action="/exportToExcel";
document.searchForm.method="POST"
document.searchForm.submit();​

}

 

컨트롤러 에서는 request.getParameter를 통해 JSP에서 POST로 넘어온 값을 받아 사용한다.

@RequestMapping(value = "/toExcel", method = RequestMethod.POST)
 public ModelAndView toExcel(HttpServletRequest req, HttpSession session) {

ModelAndView result = new ModelAndView();
Map<String, String> param = new HashMap<String, String>();

param.put("some",req.getParameter("some"));    //where에 들어갈 조건

 

List list = monitorSvc.exportToExcel(param); //쿼리

result.addObject("list",list); // 쿼리 결과를 model에 담아줌

 

Calendar now = new GregorianCalendar();
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int MILLISECOND = now.get(Calendar.MILLISECOND);
StringBuffer str = new StringBuffer();
str.append( year ).append( month ).append( day ).append( hour ).append( minute ).append( second ).append( MILLISECOND );
req.setAttribute("filename", str);​ //고유한 파일명을 위해 현재시간을 넘겨줌 

 

result.setViewName("/exportToExcel");// 엑셀로 출력하기 위한 jsp 페이지

 

return result;

 

}

 

exportToExcel.jsp

 

페이지 맨위에

 

<%@ page language="java" contentType="application/vnd.ms-excel; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

을 넣어준다.

<head>태그 사이에

 

<% 

  String filename = request.getAttribute("filename").toString();
  response.setHeader("Content-Type", "application/vnd.ms-xls");
  response.setHeader("Content-Disposition", "inline; filename=Monitoring_" + filename + ".xls");
%>​ 

 

컨트롤러에서 filename으로 넘긴 시간을 받아와

파일명에 붙여준다

Monitoring_2014082711~~~~.xls의 이름으로 다운로드가 진행된다.

 

<body>안에 table을 그려주면 그 모양대로 엑셀파일로 출력이 된다.

<table border="1">

<tr>

<th>생성시간</th>

<th>VM이름</th>

.

.

.

</tr>

<c:forEach items="${list}" var="detail" varStatus="status">

<tr>

<td><c:out value="${detail.create_time}" escapeXml="false"/></td>
<td><c:out value="${detail.vm_name}" escapeXml="false"/></td>

.

.

.

</tr>

</table>

 

위와 같이 작성하면

A        B

내용   내용

 

형식의 엑셀 파일이 만들어 진다.

 

엑셀 출력 버튼을 클릭하면

 

 

컨트롤러에서 쿼리한 값을 모델로 ExportToExcel.jsp 페이지에 전달 하게 되고

자동으로 저장 화면이 열린다.

 

출력결과

 

 

 

 

 

 

 

AD
관리자
2015-09-28 22:56
SHARE