[Spring] [Excel] 웹에서 DB를 엑셀파일로 추출시키기.

2017. 8. 24. 14:10·FrameWork/Spring
728x90
반응형

 

<!-- [dependency 추가]  -->
<dependency>
    <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
     <version>3.14</version>
</dependency>

Mapper를 만들고,
C11ReceiptVO - 도메인 생성 만들고,

액셀에서 각 4가지 카테고리별로 4가지 시트로 생성시킬 것이다.

//: [C11EvaluationExcelView.Java]
public class C11EvaluationExcelView extends AbstractExcelView  {

    private static final Logger logger = LoggerFactory.getLogger(C11EvaluationExcelView.class);


    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        logger.debug("[EvaluationExcelView] START >>>>>>>>>>>>>>>>>>>>>>>>>> ");

        Map<String, Object> map = (Map<String, Object>) model.get("excelMap");
        
        List<C11ReceiptVO> product = (List<C11ReceiptVO>) map.get("product");
        List<C11ReceiptVO> system = (List<C11ReceiptVO>) map.get("system");
        List<C11ReceiptVO> poster = (List<C11ReceiptVO>) map.get("poster");
        List<C11ReceiptVO> cali = (List<C11ReceiptVO>) map.get("cali");
        List<C11ReceiptVO> essay = (List<C11ReceiptVO>) map.get("essay");
        
        String title = "심사 결과";
        
        List<String> aStr = new ArrayList<String>();
        aStr.add("번호");
        aStr.add("접수번호");
        aStr.add("대상");
        aStr.add("그룹");
        aStr.add("심사위원1");
        aStr.add("심사위원2");
        aStr.add("심사위원3");
        aStr.add("심사위원4");
        aStr.add("심사위원5");
        aStr.add("심사위원6");
        aStr.add("총점");
        aStr.add("평균");

        createSheetWithData(workbook, "제품아이디어", aStr, product);
        createSheetWithData(workbook, "설비아이디어", aStr, system);
        createSheetWithData(workbook, "포스터", aStr, poster);
        createSheetWithData(workbook, "캘리그라피", aStr, cali);
        createSheetWithData(workbook, "에세이", aStr, essay);
        
        
        String excelName= URLEncoder.encode(title,"UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "ATTachment; Filename=" + excelName + ".xls");
        
        logger.debug("[EvaluationExcelView] END >>>>>>>>>>>>>>>>>>>>>>>>>> ");
        
    }

    private void createSheetWithData(HSSFWorkbook workbook, String title, List<String> aStr, List<C11ReceiptVO> data) {
boolean isVO = false;
        
        if(data.size() > 0) {
            Object obj = data.get(0);
            isVO = obj instanceof C11ReceiptVO;
        }
        
        Sheet sheet = workbook.createSheet(title);
        sheet.setDefaultColumnWidth(16);
        
        Font bold11 = workbook.createFont();
        bold11.setBold(true);
        bold11.setFontHeightInPoints((short) 11);
        
        CellStyle cs = workbook.createCellStyle();
        cs.setAlignment(CellStyle.ALIGN_CENTER); 
        cs.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);  
        cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cs.setFont(bold11);
        
        CellStyle defaultCs = workbook.createCellStyle();
        defaultCs.setAlignment(CellStyle.ALIGN_CENTER); 
        
        Font boldFont16 = workbook.createFont();
        boldFont16.setBold(true);
        boldFont16.setFontHeightInPoints((short) 16);
        
        CellStyle bold16 = workbook.createCellStyle();
        bold16.setFont(boldFont16);
        
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellStyle(bold16);
        titleCell.setCellValue("<" + title + "> 심사결과"); // 첫번째 셀에 텍스트 입력
        
        Row header = sheet.createRow(2);
        for (int j=0; j<aStr.size(); j++) {
            Cell cell = header.createCell(j);
            cell.setCellStyle(cs);
            cell.setCellType(Cell.CELL_TYPE_STRING);  
            cell.setCellValue(aStr.get(j));
        }
        
        for (int i=0; i<data.size(); i++) {
            if (isVO) {
                C11ReceiptVO vo = (C11ReceiptVO)data.get(i);
                
                for (int k=0; k<aStr.size(); k++) {
                    Row courseRow = sheet.createRow(i + 3);
                    courseRow.createCell(0).setCellValue(i + 1);
                    courseRow.createCell(1).setCellValue(vo.getIdx());
                    courseRow.createCell(2).setCellValue(vo.getTarget());
                    courseRow.createCell(3).setCellValue(vo.getGroup());
                    courseRow.createCell(4).setCellValue(vo.getValuer1());
                    courseRow.createCell(5).setCellValue(vo.getValuer2());
                    courseRow.createCell(6).setCellValue(vo.getValuer3());
                    courseRow.createCell(7).setCellValue(vo.getValuer4());
                    courseRow.createCell(8).setCellValue(vo.getValuer5());
                    courseRow.createCell(9).setCellValue(vo.getValuer6());
                    courseRow.createCell(10).setCellValue(vo.getTotal());
                    courseRow.createCell(11).setCellValue(vo.getAvg());
                }
            }
        }
    }
}

* HSSFWork 객체는 xls, XSSFWork 객체는 xlsx 확장명으로 가능하고 둘다 가능하게 끔 하려면 Workfactory가 필요하다.

[Controller]

@RequestMapping(value="/evaluation", method = {RequestMethod.GET}, produces = "application/json; charset=UTF-8")
    public ModelAndView evaluation() {
        Map<String, Object> param = new HashMap<String, Object>();

        param.put("productType", "0");
        for(int i = 1; i <= 6; i++) {
            param.put("valuer"+i, "test"+i);
        }
        List<C11ReceiptVO> product = loginService.getExcelBuild(param);
        System.out.println(">>>>>>>>>>"+product);
        param.put("productType", "1");
        for(int i = 7; i <= 12; i++) {
            param.put("valuer" + (i - 6), "test"+i);
        }
        List<C11ReceiptVO> system = loginService.getExcelBuild(param);

        param.put("productType", "2");
        for(int i = 13; i <= 18; i++) {
            param.put("valuer" + (i - 12), "test"+i);
        }
        List<C11ReceiptVO> poster = loginService.getExcelBuild(param);

        param.put("productType", "3");
        for(int i = 19; i <= 24; i++) {
            param.put("valuer" + (i - 18), "test"+i);
        }
        List<C11ReceiptVO> cali = loginService.getExcelBuild(param);

        param.put("productType", "4");
        for(int i = 25; i <= 30; i++) {
            param.put("valuer" + (i - 24), "test"+i);
        }
        List<C11ReceiptVO> essay = loginService.getExcelBuild(param);
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("product", product);
        map.put("system", system);
        map.put("poster", poster);
        map.put("cali", cali);
        map.put("essay", essay);
        return new ModelAndView(new C11EvaluationExcelView(), "excelMap", map);
    }

 

 

728x90
반응형

'FrameWork > Spring' 카테고리의 다른 글

[SPRING] HTML5 SOCKET 통신 [sample]  (0) 2017.12.11
[SPRING] AOP를 이용하여 어노테이션(annotation) 만들기(활용 / 사용법)  (0) 2017.12.04
[SPRING] 스프링과 마이바티스 에서 다중 데이타소스 사용하기  (0) 2017.10.19
[Spring, JAVA] 파일 복사(FileChannel 이용)  (0) 2017.09.21
[SPRING] FTP서버의 이미지 프리뷰  (0) 2017.08.28
'FrameWork/Spring' 카테고리의 다른 글
  • [SPRING] AOP를 이용하여 어노테이션(annotation) 만들기(활용 / 사용법)
  • [SPRING] 스프링과 마이바티스 에서 다중 데이타소스 사용하기
  • [Spring, JAVA] 파일 복사(FileChannel 이용)
  • [SPRING] FTP서버의 이미지 프리뷰
밍글링글링
밍글링글링
mingling - 밍글링, 밍글밍글링. 코드와 어우러지다. IT/ 프로그래밍/소스
    반응형
    250x250
  • 밍글링글링
    mingling
    밍글링글링
  • 전체
    오늘
    어제
    • 밍글링글링 (407) N
      • Flutter (2)
      • 일상생활 (8)
        • 리뷰 (1)
        • 생활정보 (4)
        • 맛집 (0)
        • 여행 (0)
        • 모든정보 (3)
      • JAVA (126)
        • 개념 (6)
        • 예제 (115)
        • Exception (2)
      • C (1)
        • C (1)
        • C++ (0)
        • C# (0)
      • JS (29)
        • JavaScript (18)
        • JQuery (5)
        • AJax (0)
        • NODE.JS (6)
        • Angular.JS 2.0 (0)
      • WEB (87)
        • HTML (6)
        • CSS (61)
        • JSP (20)
        • JSTL (0)
      • FrameWork (8)
        • Spring (8)
        • BootStrap (0)
        • MyBATIS (0)
        • JUnit (0)
      • 외부 라이브러리 (5)
      • 공유 소스 관리 (5)
        • Git (5)
        • SVN (0)
      • 빅데이터 프로그래밍 (37)
        • Python (37)
        • R Programming (0)
      • DB (7)
        • ORACLE (0)
        • MySql (6)
      • Development Tools (7)
        • StarUML (0)
        • eXERD (0)
        • Eclipse (4)
      • SKILL (6)
        • Migration (0)
        • Security (6)
      • MicroSoft (0)
        • Excel (0)
        • Word (0)
      • Android (0)
      • Server (21)
        • Ubuntu (5)
        • Linux (15)
      • IOS (0)
      • XML (0)
      • 미디어 (0)
      • 공지사항 (3)
      • NETWORK (1)
      • 게임 (4)
        • 피파 (1)
        • 리니지M (0)
        • 배틀그라운드 (1)
        • 듀랑고 (2)
      • 세상 이슈 (6)
      • 일렉트론 (0)
      • 대회 소식 (4)
      • 업무 (2)
      • Express, Vue (6)
      • docker (11)
      • svelte (3)
      • 블록체인 (1)
      • IT (10) N
      • Rust (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    API 설계
    React Compiler
    AI 코딩 에이전트
    자바 클래스
    ubuntu
    클론코딩
    VS Code 팁
    nginx ssl 적용
    ssl 인증서 발급
    vscode
    docker
    mysql db
    servlet class
    css transition
    rust linux
    css block
    proxy pass
    Extension Bisect
    css tb
    css perspective
    Node
    nginx
    css list
    lang rust
    자바 배열
    svelte
    브라우저 자동화
    자바 for문
    에디터 팁
    vue 설치
    Rust lang
    SSL 인증서
    nginx ssl 설정
    vue cli
    자바 객체 지향
    러스트
    프런트엔드
    spring java
    자바 생성자
    jsp parameter
    css float
    css table
    Java Array
    gitlab 설치
    jsp include
    자바 exception
    리눅스 설치
    티스토리 자동화
    오류
    java casting
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
밍글링글링
[Spring] [Excel] 웹에서 DB를 엑셀파일로 추출시키기.
상단으로

티스토리툴바