자바(JSP)로 엑셀파일 만드는 방법을 쭉 찾아보니 가장 많이 나오는 쉬운 방법이 html을 이용해서 표를 만들고 저장할 때 확장자를 xls 로 지정한다음 내려받기 하거나, JSP 의 헤더정보를 response.setHeader("Content-Disposition", "attachment; filename=excel.xls"); 와 같은 형태로 지정하는 방법이 나온다.
※ JSP 주소를 호출했을 때 엑셀로 다운로드가 되게 하는 샘플 jsp 코드
<%@ page contentType="application/vnd.ms-excel;charset=euc-kr" %>
<%
//중요한 사항 : "attachment; filename=excel.xls" 로 적으면 excel.xls 파일이 생성되고 다운로드된다.
//의심하지 말고 아래줄은 그냥 적어요
//모든 HTML은 Excel 파일형식으로 변환됨 (편하지 않나요?)
response.setHeader("Content-Disposition", "attachment; filename=excel.xls");
response.setHeader("Content-Description", "JSP Generated Data");
%>
<html>
<head>
<title>HTML코드가 엑셀파일변환</title>
</head>
<body>
<table border=1> <!-- border=1은 필수 excel 셀의 테두리가 생기게함 -->
<tr bgcolor=#CACACA> <!-- bgcolor=#CACACA excel 셀의 바탕색을 회색으로 -->
<td colspan=3><H3>제목을 적어줍니다</H3></td>
</tr>
<tr bgcolor=yellow>
<td>삼</td> <td>육</td> <td>구</td>
</tr>
<tr>
<td>1</td> <td>2</td> <td>3</td>
</tr>
<tr>
<td>4</td> <td>5</td> <td>6</td>
</tr>
<tr>
<td>7</td> <td>8</td> <td>9</td>
</tr>
</table>
</body>
</html>
<!--
참고한 사이트 :
http://blog.naver.com/gaggaii/140008297580
-->
이렇게 하면 위의 jsp 주소를 호출하면 엑셀파일 받기 창이 뜬다. 이 때 표에 속성을 주면 엑셀에서 열었을 때 모두 적용이 된다. 단, 실제로는 html 파일을 엑셀에서 여는 것이므로 엑셀에서 열기 할 때 경고가 뜬다. 그냥 무시하고 열면 된다. 엑셀에서 작업을 하거나 저장할 때는 "다른이름으로 저장 / Excel 통합문서로 저장" 을 해주면 더이상 경고는 뜨지 않는다.
내 경우는 html로 시작해서 html로 끝나는 부분까지를 파일로 저장한 다음 아래 있는 방법으로 자바코드에서 다운받도록 했는데 이 때 만약 엑셀에서 열었을 때 한글이 깨지는 현상이 발생하면 아래 코드를 생성하는 html 맨위에 써주면 된다.
<meta http-equiv="Content-Type" content="application/vnd.ms-excel;charset=euc-kr">
자바코드에서 다운받는 방법은 위와같은 포맷으로 파일을 만들되 확장자를 xls 로 지정해서 저장을 한다. 그리고 해당 파일을 다운받도록 하면 된다.
아래 코드는 스프링의 컨트롤러 중 ModelAndView 에 설정되어있는 코드다 (현재 사용중인 코드에서 일부 발췌)
public ModelAndView statisticsUsage(HttpServletRequest request, HttpServletResponse response) throws Exception {
// ........... 중간 생략 ...................
fileName = "1.xls"; // 테스트용으로 하드코딩
filePath = "/test/"; // 테스트용으로 하드코딩
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
javax.servlet.ServletOutputStream servletoutputstream1 = response.getOutputStream();
File file2 = new File(filePath + fileName);
try {
boolean isDown = dumpFile(file2, servletoutputstream1);
if (isDown) {
servletoutputstream1.flush();
servletoutputstream1.close();
}
} finally {
try {
servletoutputstream1.close();
} catch (Exception e) {
}
}
return new ModelAndView("DummyView");
}
private boolean dumpFile(File realFile, OutputStream outputstream) {
byte readByte[] = new byte[4096];
boolean isDown = false;
BufferedInputStream bufferedinputstream = null;
try {
bufferedinputstream = new BufferedInputStream(new FileInputStream(realFile));
int i;
while ((i = bufferedinputstream.read(readByte, 0, 4096)) != -1) {
outputstream.write(readByte, 0, i);
}
bufferedinputstream.close();
isDown = true;
} catch (Exception _ex) {
try {
bufferedinputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// _ex.printStackTrace();
isDown = false;
}
return isDown;
}