반응형

poi를 활용한 엑셀 다운로드(다른 이름으로 저장) 폴더 및 파일 명 지정

 

서버 환경 
: java1.8
: 전자정부 프레임워크 - 개발자용 개발환경 32bit/64bit(Implementation Tool) Version 3.9.0 

: tomcat8

 

1. pom.xml에 Dependency 추가

<!-- Excel Read/Write 를 위한 Dependency 추가 -->
<dependency>
<groupId>org.apachepoi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>

 

 

2. devfootprint.tistory.com/56

 

전자정부프레임워크 maven 클린 프로젝트 클린 리빌드

war 파일 삭제 후 생성 프로세스 dependency 추가했을 경우 0. Maven > Update Project : pom.xml에 dependency를 내 로컬 pc에 다운로드 그렇지 않을 경우엔 0번 스킵해도 됨 1. 프로젝트 우클릭 > Run as..

devfootprint.tistory.com

3. java 소스

@RequestMapping(value = "/data/downloadDataInfo.do")
public void downloadDataInfo(@RequestParam HashMap<String, Object> commandMap, HttpServletResponse response) throws Exception {

    FileOutputStream fileOut = null;
    // Workbook 생성
    Workbook xlsWb = new HSSFWorkbook(); // Excel 2007 이전 버전
    String sheetname = "sheet1";
    Sheet sheet = xlsWb.createSheet(sheetname);
			
    Font font = xlsWb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("맑은고딕");
			
    sheet.setColumnWidth(1, 50*256);
    CellStyle style = xlsWb.createCellStyle();
    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			
    Row row = null;
    Cell cell = null;
                    
    // 첫번째 행추가
    row = sheet.createRow(0);
    row.setHeight((short)500);
            
    // 첫번째행에 첫번째 컬럼 값 생성
    cell = row.createCell(0);
    cell.setCellValue("test1");
    cell.setCellStyle(style);

    // 첫번째행에 두번째 컬럼 값 생성
    cell = row.createCell(1);
    cell.setCellValue("test2");
    cell.setCellStyle(style);            
            
	         
    response.setContentType("application/octet-stream;");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes(), "UTF-8") + "\"");
    response.setHeader("Pragma", "no-cache;");
    response.setHeader("Expires", "-1;");

    // excel 파일 저장
    try {
        fileOut = new FileOutputStream("test.xls");
        xlsWb.write(response.getOutputStream());
        fileOut.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fileOut != null) {
            fileOut.close();
        }
    }
}
반응형

+ Recent posts