by Nathan

엑셀 다운로드(gradle, poi3.7) 본문

Programming/JAVA

엑셀 다운로드(gradle, poi3.7)

넷쓴 2018. 7. 30. 13:54

js

1
2
3
function excelDown(){
    location.href = "/exceldownload";
}
cs




controller

1
2
3
4
5
@GetMapping("/exceldownload")
public void excelDownload(VO vo, HttpServletResponse response) {
    List<Vo> dataList = service.getList(vo); // 데이터 조회
    service.downloadData(dataList, response); // 엑셀 생성 및 다운로드
}
cs



service

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public void downloadCustomerInfo(List<Vo> dataList, HttpServletResponse response) {
        
    // 오늘날짜
    String strToday = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
    
    // Sheet 생성
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("고객목록_"+strToday);
    XSSFRow row = null;
    XSSFCell cell = null;
    int rowCount = 0;
    int cellCount = 0;
 
    // 첫번째 로우 폰트 설정
    Font headFont = workbook.createFont();
    headFont.setFontHeightInPoints((short11);
    headFont.setFontName("돋움");
 
    // 첫번째 로우 셀 스타일 설정
    CellStyle headStyle = workbook.createCellStyle();
    headStyle.setAlignment(CellStyle.ALIGN_CENTER);
    headStyle.setFont(headFont);
    headStyle.setBorderBottom(CellStyle.BORDER_THIN);
    headStyle.setBorderLeft(CellStyle.BORDER_THIN);
    headStyle.setBorderRight(CellStyle.BORDER_THIN);
    headStyle.setBorderTop(CellStyle.BORDER_THIN);
    headStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
 
    // 바디 폰트 설정
    Font bodyFont = workbook.createFont();
    bodyFont.setFontHeightInPoints((short9);
    bodyFont.setFontName("돋움");
 
    // 바디 스타일 설정
    CellStyle bodyStyle = workbook.createCellStyle();
    bodyStyle.setFont(bodyFont);
    bodyStyle.setWrapText(true);
    bodyStyle.setBorderBottom(CellStyle.BORDER_THIN);
    bodyStyle.setBorderLeft(CellStyle.BORDER_THIN);
    bodyStyle.setBorderRight(CellStyle.BORDER_THIN);
    bodyStyle.setBorderTop(CellStyle.BORDER_THIN);
 
    // 헤더 생성
    row = sheet.createRow(rowCount++);
    String[] headers = {"컬럼1","컬럼2","컬럼3","컬럼4","컬럼5"};
    for(int i=0; i<headers.length; i++){
        cell = row.createCell(cellCount++);
        cell.setCellStyle(headStyle);
        cell.setCellValue(headers[i]);
    }
    
    // 데이터 생성
    for (Vo vo : dataList) {
        row = sheet.createRow(rowCount++);
        cellCount = 0;
        int nCount = 0;
 
        // 바디 셀에 데이터 입력, 스타일 적용
        cell = row.createCell(cellCount++);
        cell.setCellStyle(bodyStyle);
        cell.setCellValue(vo.getCol1());   // 컬럼1
        
        cell = row.createCell(cellCount++);
        cell.setCellStyle(bodyStyle);
        cell.setCellValue(vo.getCol2());  // 컬럼2
        
        cell = row.createCell(cellCount++);
        cell.setCellStyle(bodyStyle);
        cell.setCellValue(vo.getCol3());  // 컬럼3
        
        cell = row.createCell(cellCount++);
        cell.setCellStyle(bodyStyle);
        cell.setCellValue(vo.getCol4());    // 컬럼4
        
        cell = row.createCell(cellCount++);
        cell.setCellStyle(bodyStyle);
        cell.setCellValue(vo.getCol5());  // 컬럼5
    }
    
    // 셀 와이드 설정
    for (int i=0; i<headers.length; i++){
        sheet.autoSizeColumn(i, true);
        if(i == 11){ // 컬럼별 넓이정의
            sheet.setColumnWidth(i, 7000);
        }
    }
    
    // 엑셀생성 경로설정 및 자원종료
    String filePath = "";
    String filename = "";
    try {
        filePath = uploadsRoot + "/static/download/excel/"+strToday+"/"// file 생성 위치 
        filename = "test_"+System.currentTimeMillis()+".xlsx"// 생성될 파일 이름
        
        // 엑셀 파일 생성
        File fDir = new File(filePath);
        if (!fDir.exists()) { // 디렉토리 없으면 생성
            fDir.mkdirs(); 
        }
 
        FileOutputStream fout = new FileOutputStream(filePath + filename);
        workbook.write(fout);
        fout.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    fm.fileDownload(filePath, filename, response);
}
cs





fileDownload 함수

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
public void fileDownload(String filePath, String filename, HttpServletResponse response){
    try {
        File f = new File(filePath+filename);
        if (!f.exists()) {
            System.out.println("error"); // 존재하지 않는 파일 다운로드
        }
 
        filename = new String(filename.getBytes("euc-kr"), "8859_1");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition""attachment;filename="+ filename);
 
        // 파일 내용을 클라이언트에 전송
        byte[] b = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
        OutputStream os = response.getOutputStream();
 
        int n;
        while ((n = bis.read(b, 0, b.length)) != -1) { // 파일을 모두 읽으면 -1리턴
            os.write(b, 0, n);
        }
        os.flush();
        os.close();
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
cs


'Programming > JAVA' 카테고리의 다른 글

엑셀 업로드(gradle, poi3.7)  (0) 2018.07.30
HTTP request  (0) 2017.03.20
StringTokenizer  (0) 2017.03.17
Bubble sort  (0) 2017.03.17
request.getRemoteAddr() ipv4로 받기  (0) 2016.06.13
Comments