자바 엑셀 파일 다운로드

구성욱·2022년 12월 29일
0

SpringBoot

목록 보기
3/3

※ 기준

  • IntelliJ Ultimate
  • Spring (v2.2.6)
  • JDK (1.8)
  • Controller 단 작업

※ 요약
1. 바로 다운로드 되게끔 -> return Type void
2. 제목 안깨지게 동적으로 설정할거면 StringBuffer와 인코딩 타입 설정
3-1. csv의 경우 데이터 StringBuffer에 쉼표로 구분해서 append
3-2. xlsx의 경우 라이브러리로 엑셀 파일 생성
4. response ContentType, Header 설정

@PostMapping("{값}")
public void downloadCSV(HttpServeletRequest request,
						HttpServeletResponse response,
                        CustomModel cmodel) {
	try {
    	// 넘어 온 파라미터 유효성 검사
    	if ( cmodel.getValue1().isEmpty() ) {
        	throw new Exception();
        }
        else {
        	List<cmodel> modelList = customService.selectExample(cmodel);
        }
        
        StringBuffer bf = new StringBuffer();
        bf.append("NO, 헤더1, 헤더2, 헤더3\n");		// 쉼표로 구분
        
        int cnt
        
        for (DictModel item : dict.getDtnrList()) {
               bf.append(Integer.toString(cnt) + ","
                        + "\"" +item.1 + "\"" + ","
                        + item.2 + ","
                        + item.3 + ","
                        + item.4 + ","
                        + "\n");

                cnt++;
        }


            response.setContentType("ms-vnd/excel");
            response.setHeader("Content-Disposition", "attachment;filename=\"file.csv\"");

            response.setContentType("text/csv");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNm);
            response.setHeader("Content-Type", "text/csv; charset=MS949");

            OutputStream out = response.getOutputStream();;
            out.write(bf.toString().getBytes("MS949"));
            out.flush();
            out.close();
            bf.setLength(0);
        
    }
    catch (Exception e) {
    	throw new Exception e;
    }
    finally {
    
    }
}

엑셀 파일은 XSSFWorkBook 이나 엑셀 모듈에 맞게끔 작성

profile
아무것도 몰라요우

0개의 댓글