본문 바로가기
JAVA

[Java] 자바 엑셀 파일 생성 후 다운로드 예제(Excel Create And Download) Apache Poi Excel Create

by DionKo 2021. 7. 23.

개발을 진행하다 보면 고객의 요청으로 특정 데이터를 추출하여 엑셀 파일을 생성하여 다운로드 받는 기능을 만드는 일이 종종있습니다. 엑셀 파일 생성 후 다운로드의 경우 크게 어렵지 않으며 자바에서 셋팅을 어떻게 해주냐에 따라 폰트, 글자 크기, 글자 배치 등을 설정할 수 있습니다. 오늘은 간단한 방법으로 자바 엑셀파일 다운로드에 대해서 알아보겠습니다.

 

 

1. GET 방식의 API 생성

@GetMapping("/get/excel/users")
public void excel(HttpServletRequest req, HttpServletResponse res) {
  try {
  	// 엑셀 다운로드 함수 
  	TestUtil.excelDownload(res);
  }catch(Exception e) {
  	e.printStackTrace();
  }
}

 

2. TestUtil 클래스에 엑셀 다운로드 메서드 생성

public static void excelDownload(HttpServletResponse res) {
	List<TestVo> listData = new ArrayList<TestVo>();
	TestVo testVo = new TestVo();
		
	testVo.setUserName("홍길동");
	testVo.setUserAge("20");
	testVo.setAddress("서울시");
	listData.add(testVo);
		
	testVo = new TestVo();
	testVo.setUserName("김길동");
	testVo.setUserAge("25");
	testVo.setAddress("부산시");
	listData.add(testVo);
		
	testVo = new TestVo();
	testVo.setUserName("강길동");
	testVo.setUserAge("23");
	testVo.setAddress("충북");
	listData.add(testVo);
	
	if(listData != null && listData.size() > 0) {
		final String fileName = "userList.xlsx";
		
		/* 엑셀 그리기 */
		final String[] colNames = {
			"No", "성명", "나이", "거주지"
		};
		
		// 헤더 사이즈
		final int[] colWidths = {
			3000, 5000, 5000, 3000
		};
		
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = null;
		XSSFCell cell = null;
		XSSFRow row = null;
		
		//Font
		Font fontHeader = workbook.createFont();
		fontHeader.setFontName("맑은 고딕");	//글씨체
		fontHeader.setFontHeight((short)(9 * 20));	//사이즈
		fontHeader.setBoldweight(Font.BOLDWEIGHT_BOLD);	//볼드(굵게)
		Font font9 = workbook.createFont();
		font9.setFontName("맑은 고딕");	//글씨체
		font9.setFontHeight((short)(9 * 20));	//사이즈
		// 엑셀 헤더 셋팅
		CellStyle headerStyle = workbook.createCellStyle();
		headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
		headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		headerStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
		headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		headerStyle.setFont(fontHeader);
		// 엑셀 바디 셋팅
		CellStyle bodyStyle = workbook.createCellStyle();
		bodyStyle.setAlignment(CellStyle.ALIGN_CENTER);
		bodyStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		bodyStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		bodyStyle.setFont(font9);
		// 엑셀 왼쪽 설정
		CellStyle leftStyle = workbook.createCellStyle();
		leftStyle.setAlignment(CellStyle.ALIGN_LEFT);
		leftStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
		leftStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		leftStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		leftStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		leftStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		leftStyle.setFont(font9);
		
		//rows
		int rowCnt = 0;
		int cellCnt = 0;
		int listCount = listData.size();
		
		// 엑셀 시트명 설정
		sheet = workbook.createSheet("사용자현황");
		row = sheet.createRow(rowCnt++);
		//헤더 정보 구성
		for (int i = 0; i < colNames.length; i++) {
			cell = row.createCell(i);
			cell.setCellStyle(headerStyle);
			cell.setCellValue(colNames[i]);
			sheet.setColumnWidth(i, colWidths[i]);	//column width 지정
		}
		//데이터 부분 생성
		for(TestVo vo : listData) {
			cellCnt = 0;
			row = sheet.createRow(rowCnt++);
			// 넘버링
			cell = row.createCell(cellCnt++);
			cell.setCellStyle(bodyStyle);
			cell.setCellValue(listCount--);
			// 성명
			cell = row.createCell(cellCnt++);
			cell.setCellStyle(bodyStyle);
			cell.setCellValue(vo.getUserName());
			// 나이
			cell = row.createCell(cellCnt++);
			cell.setCellStyle(bodyStyle);
			cell.setCellValue(vo.getUserAge());
			
			// 주소
			cell = row.createCell(cellCnt++);
			cell.setCellStyle(bodyStyle);
			cell.setCellValue(vo.getAddress());
		}
		res.setContentType("application/vnd.ms-excel");
		// 엑셀 파일명 설정
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		try {
			workbook.write(res.getOutputStream());
		} catch(IOException e) {
			e.printStackTrace();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

- 자바 소스는 간단하며 소스 내부에 설명이 되어있기 때문에 설명은 제외 하겠습니다.

 

3. 자바스크립트에서 호출

location.href="/get/excel/users";

 

- 자바스크립트에서 엑셀 다운로드 API를 GET 방식으로 호출 시 바로 엑셀을 생성하여 다운로드 받습니다. 추출 데이터가 많은 분들은 location.href를 호출하기 전에 loading 이미지를 보여줘서 이질감을 낮추는게 좋을거 같습니다.