본문 바로가기
자바

자바 데이터 엑셀로 출력하기

by 처리2 2020. 4. 1.
반응형

//엑셀 칼럼 지정 

String[] headlist = {"count","title","name",....};

 

//엑셀 업로드
public void ExcelListWorkBook(List<HashMap<String, Object>> list,HttpServletResponse response, String[] headerList,String filename) throws Exception{
SXSSFWorkbook workbook = new SXSSFWorkbook();

// 시트 생성
        SXSSFSheet sheet = workbook.createSheet("Result");

        
        // 테이블 헤더용 스타일
        CellStyle headStyle = workbook.createCellStyle();
        // 가는 경계선을 가집니다.
        headStyle.setBorderTop(BorderStyle.THIN);
        headStyle.setBorderBottom(BorderStyle.THIN);
        headStyle.setBorderLeft(BorderStyle.THIN);
        headStyle.setBorderRight(BorderStyle.THIN);
        // 데이터는 가운데 정렬합니다.
        headStyle.setAlignment(HorizontalAlignment.CENTER);

        // 데이터용 경계 스타일 테두리만 지정
        CellStyle bodyStyle = workbook.createCellStyle();
        bodyStyle.setBorderTop(BorderStyle.THIN);
        bodyStyle.setBorderBottom(BorderStyle.THIN);
        bodyStyle.setBorderLeft(BorderStyle.THIN);
        bodyStyle.setBorderRight(BorderStyle.THIN);
        
        // 헤더 행 생
        Row headerRow = sheet.createRow(0);
        Cell headerCell;
        
        for(int i=0;i<headerList.length;i++) {
         headerCell = headerRow.createCell(i); 
            headerCell.setCellValue(headerList[i]);
        }
        
        Row bodyRow = null;
        Cell bodyCell = null;
        
        //칼럼에 맞게 등록
        bodyCell =  ExcelValueInsert(list,bodyRow,bodyCell,sheet,type);
        
        
        // 컨텐츠 타입과 파일명 지정
        response.setContentType("ms-vnd/excel");
        response.setHeader("Content-Disposition", "attachment;filename="+filename+"_Excel.xls");

        // 엑셀 출력
        workbook.write(response.getOutputStream());

        workbook.close();
}

 

 

 

 

 

public Cell ExcelValueInsert(List<HashMap<String, Object>> list, Row bodyRow, Cell bodyCell, SXSSFSheet sheet, String type ) throws Exception {
for(int i = 0; i< list.size(); i++) {
         HashMap listData = list.get(i);

         // 행 생성
            bodyRow = sheet.createRow(i+1);
            // 데이터 번호 표시
            bodyCell = bodyRow.createCell(0);
            bodyCell.setCellValue(i + 1);
            bodyCell = bodyRow.createCell(1);

    }
 return bodyCell;

}

 

이런식으로 HashMap리스트를 넣어서 하나씩 원하는 칼럼에 넣을 수 있습니다~~ ㅎㅎ

 

반응형

댓글