[Java] 엑셀 단일 데이터 출력

BBANG-JUN·2020년 10월 15일
0

Java

목록 보기
3/6
post-thumbnail

step1. POI 라이브러리를 적용


        <!-- poi -->

        <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi</artifactId>

            <version>3.17</version>

        </dependency>

step2. JSP에서 submit을 활용하며 url에 form:action

Controller

@RequestMapping(value = "/sfc/dlvy/selectDataLabel.do")

public void selectDataLabelDownload(@ModelAttribute("data") DlvyVO dlvyVO,  HttpServletRequest request, HttpServletResponse response) throws Exception {

	    Workbook wb = dlvyService.downloadExcel(dlvyVO);

		// 컨텐츠 타입과 파일명 지정

	    response.setContentType("ms-vnd/excel");

	    response.setHeader("Content-Disposition", "attachment;filename=labeData.xls");



	    // 엑셀 출력

	    wb.write(response.getOutputStream());

	    wb.close();

	}

설명 : downloadExcel()를 이용하여 Workbook형식으로 워크시트를 그려준 후 wb에 저장합니다.
이후, 컨텐츠 타입 및 파일명을 적고 엑셀을 출력시키면 다운로드 기능이 됩니다.

step3. downloadExcel() : 데이터 적용

Service

public Workbook downloadExcel(DlvyVO dlvyVO){

		// 엑셀 구성 및 시트명

		Workbook xlsWb = new HSSFWorkbook();

		Sheet sheet = xlsWb.createSheet("라벨"); // 시트명



		// 행, 열

		Row row = null;

		Cell cell = null;

		int rowIdx = 0;

		int cellIdx = 0;



		// title

		String[] title= { "제목", "이름" };



		// data

		String[] data = {"엑셀만들기","이병준"};



		//data : 다음과 같이 데이터베이스를 이용해 가공해줄 수도 있다.

		EgovMap customData = dlvyMapper.downloadCustomExcel(dlvyVO);

		data = new String[custom.length];

		for(int i=0; i<data.length; i++) {

			data[i] = customData.getValue(i).toString();

		}



		//title를 첫 번째 줄에 적용시킨다.

		row = sheet.createRow(rowIdx++);

		for(int i=0; i<custom.length; i++) {

			cell = row.createCell(i);

		        cell.setCellValue(custom[i]);

		        cell.setCellStyle(cellStyle(xlsWb, "title"));

		}



                // data를 두 번째 줄에 적용시킨다.

		row = sheet.createRow(rowIdx++);

	        cell = row.createCell(cellIdx++);

	        for(int i=0; i<data.length; i++) {

			cell = row.createCell(i);

		        cell.setCellValue(data[i]);

		        cell.setCellStyle(cellStyle(xlsWb, "data"));

		}



		// 셀 너비 설정 : 너비 간격을 글자에 따라 auto로 만들어준다.

		for (int i=0; i<=12; i++){

			sheet.autoSizeColumn(i);

			sheet.setColumnWidth(i, (sheet.getColumnWidth(i))+(short)1024);

		}



        return xlsWb;

	}

step4. cellStyle() : 스타일 설정

Service



//셀 스타일 설정하는 함수

public static CellStyle cellStyle(Workbook xlsWb, String kind) {

		CellStyle cs = xlsWb.createCellStyle(); // 셀

		Font f = xlsWb.createFont();  // 폰트



		//헤더 스타일 : 중앙정렬

		cs.setAlignment(HorizontalAlignment.CENTER);



		//본문 스타일 : 테두리

		cs.setBorderBottom(BorderStyle.MEDIUM);

		cs.setBorderLeft(BorderStyle.MEDIUM);

		cs.setBorderRight(BorderStyle.MEDIUM);

		cs.setBorderTop(BorderStyle.MEDIUM);



                // 조건문을 이용하여 key값에 따른 스타일을 정해줄 수도 있다.

                // kind : 매개변수("title" or "data")

		if(kind.equals("title")) {

			// 타이틀

			cs.setFillForegroundColor(IndexedColors.LIME.getIndex()); // 배경색상

			cs.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 색상적용

			f.setFontHeightInPoints((short) 11); // 글자크기

			f.setBold(true);                  // 굵기(bool)

			f.setFontName("맑은 고딕"); // 글씨체

			cs.setFont(f);                    // 폰트 Cell에 적용

		}else if(kind.equals("data")) {

			// 데이터

			f.setFontHeightInPoints((short) 11);

			f.setFontName("맑은 고딕");

			cs.setFont(f);

		}



		return cs;

	}

결과 예시

profile
🔥 머릿속으로 생각하지만 말고, 행동으로 보여줘

0개의 댓글