티스토리 뷰

JAVA

[JAVA] 파일 다운로드

gray.yoon 2017. 2. 1. 16:28

이번엔 파일 업로드가 아닌 DB데이터를 조회하여 엑셀 파일로 다운로드 기능을 포스팅 한다.


아래는 Contoller로 호출 받았을 경우 파일 명 셋팅 및 엑셀 파일을 생성하는 과정이다.


addrDataMakeExcel 메소드의 경우 파일에 쓸 데이터와 response outputStream 객체를 받는다.


outputStream 객체의 경우 workbook을 생성하기 위한 객체로 쓴다.


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
    @RequestMapping(value="/addrExcelFileDown.do")
    public void addrExcelFileDown(HttpServletRequest request, HttpServletResponse response, ModelMap model,
            @RequestParam(value="groupSeq" , required=falseString groupSeq) throws Exception{
        
        UserVo userSess = this.readUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        
        paramMap.put("userId", userSess.getUserId());
        
        if(groupSeq != null){
            paramMap.put("groupSeq", groupSeq);
            // 자신의 그룹이 아닌 호출인 경우 400오류 표출
            if! addrService.isUserAddrGroupYN(userSess.getUserId(), groupSeq)){
                response.sendError(Response.SC_BAD_REQUEST);
            }
        }
        
        // 파일명 만들기 ( "주소록"_그룹명_년월일시분초.xls)
        StringBuffer fileNameBf = new StringBuffer();
        fileNameBf.append(Constants.ADDRESS);        // 주소록
        fileNameBf.append("_");                                // _
        fileNameBf.append((groupSeq==null || "".equals(groupSeq)) ? Constants.ADDRESS_CONSTANTS.TOTAL : addrService.selectGroupInfo(paramMap).getGroupName());    // 그룹명
        fileNameBf.append("_");                                // _
        fileNameBf.append(DateUtil.getTodayDateTime("yyyyMMddHHmmss"));                                // 현재 날짜와 시분초
        fileNameBf.append(".");
        fileNameBf.append(Constants.FILE_EXTENSION.XLS.toLowerCase());                                    // 확장자
        
        // 조회한 주소록 수신자 조회
        List<AddrVO> addrVOList = addrService.selectAddrList(paramMap);
        
        /////////////////////////////////////////////////////////////////////////////////////////////
        // 엑셀파일 객체 생성
        WritableWorkbook workbook = fileInOutService.addrDataMakeExcel(addrVOList, response.getOutputStream());
        
        response.setHeader("Content-Type""application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", HttpUtil.getDisposition(fileNameBf.toString(), HttpUtil.getBrowser(request)));
        response.setHeader("Content-Transfer-Encoding""binary;");
        response.setHeader("Pragma""no-cache;");
        response.setHeader("Expires""-1;");
        
        workbook.write();
        workbook.close();
        
    }
cs


아래는 addrDataMakeExcel 메소드의 구현된 형태이다.


Workbook 객체에 데이터를 쓰는 과정이다.


크게 어렵거나 하는 부분이 없어 설명은 없어도 될 듯 하다.


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
    public WritableWorkbook addrDataMakeExcel(List<AddrVO> addrList, ServletOutputStream outputStream){
 
        // 엑셀파일 객체 생성
        WritableWorkbook workbook = null;
        
        // 시트 객체 생성
        WritableSheet sheet = null;
        
        // 셀 객체 생성
        Label label = null;
        
        
        try {
            // 파일 생성
            workbook = jxl.Workbook.createWorkbook(outputStream);
        
            // 시트 생성
            workbook.createSheet("sheet1"0);
            sheet = workbook.getSheet(0);
    
            // 셀에 쓰기 (주소록 첫번째 행 HEADER 설정 )
            label = new Label(00, Constants.FILE_HEADER_DICTIONARY.NAME);
            sheet.addCell(label);
    
            label = new Label(10, Constants.FILE_HEADER_DICTIONARY.PHONE);
            sheet.addCell(label);
            
            label = new Label(20, Constants.FILE_HEADER_DICTIONARY.EMAIL);
            sheet.addCell(label);
            
            label = new Label(30, Constants.FILE_HEADER_DICTIONARY.MEMO);
            sheet.addCell(label);
                 
                 
            // 데이터 삽입
            for(int i=0; i < addrList.size(); i++){
                AddrVO addrVO = addrList.get(i) ;
                 
                label = new Label(0, (i+1), addrVO.getName());
                sheet.addCell(label);
                 
                label = new Label(1, (i+1), addrVO.getPhoneNo());
                sheet.addCell(label);
                
                label = new Label(2, (i+1), addrVO.getEmail());
                sheet.addCell(label);
                
                label = new Label(3, (i+1), addrVO.getMemo());
                sheet.addCell(label);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return workbook;
        
    }
cs


이상으로 파일 다운로드 포스팅을 마무리 한다.


프로젝트 끝! 겨우 데드라인에 마췄지만 딱히 어려움 없이 잘 끝낸듯 하다.

'JAVA' 카테고리의 다른 글

[JAVA] 파일 읽기 (업로드)  (1) 2017.02.01
[JAVA]자바 설치 및 설정하기  (0) 2012.10.09
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함