Programing/JAVA

poi 활용 excel 파일 생성 후 다운로드 창 띄워 위치설정해 다운 받는 방법.

리커니 2015. 10. 28.
반응형

poi 활용 excel 파일 생성 후 다운로드 창 띄워 위치설정 후 다운 받는 방법.

 

이 방법에는 여러가지가 있겠지만 제가 사용한 방법은

1. poi를 사용해 임의의 위치에 엑셀 파일을 만들고

2. 만든 데이터를 다운로드 한 후

3. 임의의 위치에 만든 파일을 지우는

방법 입니다.

 

우선 poi를 활용해 임의의 위치에 엑셀 파일을 만드는 방법은 아래의 Link를 참조하세요.

 

Link : java poi 활용 json 데이터 엑셀 다운로드 기능 구현

 

위의 Link를 활용해 데이터를 엑셀 파일로 생성 했다면

이제 사용자가 지정된 위치에 다운로드 하는 기능을 구현한 코드를 보겠습니다.

 

위와 같은 경우 JSON 으로 데이터를 보내 엑셀파일을 생성후 성공했다면

resultCode 에 200을 담아 JSP로 리턴합니다.

 

그래서 그 전에 엑셀파일 생성 후 바로 다운로드 창이 뜨게 구현하려 했지만 파일스트림을 close해도 파일이 열려서

다운로드가 되지 않았다.

 

그래서 엑셀 파일 생성과 다운 클래스를 나눌 수밖에 없었다..(시간이 없었으므로)

 

다시 본론으로 들어가서

엑셀파일 생성 후 resultCode에 200 (성공) 값이 담아서 오면

다운로그 기능이 있는 함수를 실행한다.

 

[Link의 ajax 부분을 아래와 같이 수정]

$.ajax({
   type : 'POST',  
   dataType : 'json', 
   data: dataParam,
   url : '/excelDownload.do',  
   success : function(returnData) {
    if(returnData.resultCode==200){
     getFileDownload();    

     }else if(returnData.resultCode==300){
     alert("엑셀 데이터 저장에 실패하였습니다.");
    };
   },error:function(e){
    if(e.status==300){
     alert("엑셀 데이터 저장에 실패하였습니다.");
    };
   }
  }); 
 }
}​

 

그리고 아래의 function을 추가 한다.

 

function getFileDownload(){

     window.open("<c:url value='/downLoadFile.do'/>");
};​

 

[downLoadFile.java]

 

/*파일을 다운로드한다.*/
 @RequestMapping(value="/downLoadFile.do")
 public void downLoadFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
  
  String path = "D:/default/";  // Link의 자바파일에서 excel 파일이 생성된 경로
  String realFileNm = "파일명.xls";
  
  File uFile = new File(path,realFileNm);
  int fSize = (int) uFile.length();
  if (fSize > 0) {  //파일 사이즈가 0보다 클 경우 다운로드
   String mimetype = "application/x-msdownload";  //minetype은 파일확장자에 맞게 설정

   response.setContentType(mimetype);
   setDisposition(realFileNm, request, response);
   response.setContentLength(fSize);

   BufferedInputStream in = null;
   BufferedOutputStream out = null;
   
   try {
    in = new BufferedInputStream(new FileInputStream(uFile));
    out = new BufferedOutputStream(response.getOutputStream());
    FileCopyUtils.copy(in, out);
    out.flush();
   } catch (Exception ex) {
   } finally {
    if (in != null) in.close();
    if (out != null) out.close();
   }
  } else {
   response.setContentType("application/x-msdownload");

   PrintWriter printwriter = response.getWriter();
   printwriter.println("<html>");
   printwriter.println("<br><br><br><h2>Could not get file name:<br>" + realFileNm + "</h2>");
   printwriter.println("<br><br><br><center><h3><a href='javascript: history.go(-1)'>Back</a></h3></center>");
   printwriter.println("<br><br><br>&copy; webAccess");
   printwriter.println("</html>");
   printwriter.flush();
   printwriter.close();
  }
 }​

 

위에서도 말했지만, excel파일 생성 후 바로 다운로드가 되도록 구현하려 했지만

파일스트림이 닫히지 않아서인지 뭔지 다운로드를 구현한 코드가 실행되지 않았다.

 

그래서 파일 생성과 다운로드를 나누어 구현..

뭔가 아니다 싶지만, 기능상 문제는 없다.

 

 

반응형

댓글

💲 추천 글