째의 개발 기록방

[Java/Spring] Poi 엑셀 파일 다운로드(Excel _file_Download) 본문

Back End/Java, Spring

[Java/Spring] Poi 엑셀 파일 다운로드(Excel _file_Download)

째린이 2021. 11. 18. 17:37

엑셀파일로 업로드/다운로드 할 리스트 화면

 

지금 개발 진행(연습) 중인 CRUD

 

  • 엑셀파일다운로드 = 현재 화면에 뿌려져있는 데이터를 엑셀파일로 받겠다.
  • 엑셀파일업로드 = 샘플로 제공된 엑셀파일로 데이터를 가공하여 업로드 시키겠다.

 

엑셀파일다운로드 

 

  • jsp
<div>
	<a id="excelSubmit" class="button" href="javascript:fnExcelDown();">엑셀파일 다운로드</a>
</div>

엑셀파일다운로드 버튼 클릭 시 엑셀파일다운로드 함수 실행

* a말고 button 태그를 사용해도 되지만 폼이 있을때 button은 엔터키만 눌러도 전송되어지는 이슈가 있을 수 있어서

a태그를 사용했다. 

 

<form id="searchForm" action="/nfeatures/reportList.do" method="POST" style="margin-bottom:4%;"> 
		<input type="hidden" name="searchType">
		<input type="hidden" name="currPage" id="currPage" value="${currPage}">
		<span>검색 ${reportVO.reportTitle }</span>
		<select name="kwd" id="searchType" onchange="changeSearchType()">
			<option value="" selected>--전체보기--</option>
			<option value="reportTitle" <c:if test="${reportVO.searchType eq 'reportTitle'}">selected</c:if>>제목</option>
			<option value="reportContent" <c:if test="${reportVO.searchType eq 'reportContent'}">selected</c:if>>내용</option>
		</select>
		<input type="text" name="selectTxt" value="${reportVO.selectTxt}" id="selectTxt">
		<a href="javascript:searchForm();" class="search">검색</a>
		<h3>정렬</h3>
		<select name="orderByType" id="orderByType" onchange="changeSort();">
			<optgroup label="--전체보기--">
				<option value="reportTitle" <c:if test="${reportVO.orderByType eq 'reportTitle' }">selected</c:if>>제목</option>
				<option value="regId" <c:if test="${reportVO.orderByType eq 'regId' }">selected</c:if>>등록자</option>
				<option value="regDt" <c:if test="${reportVO.orderByType eq 'regDt' }">selected</c:if>>등록일</option>
			</optgroup>
		</select>
		<select name="orderBy" id="orderBy"  onchange="changeSort();">
			<optgroup label="--전체보기--">
				<option value="orderByTop" <c:if test="${reportVO.orderBy eq 'orderByTop' }">selected</c:if>>오름차순</option>
				<option value="orderByRow" <c:if test="${reportVO.orderBy eq 'orderByRow' }">selected</c:if>>내림차순</option>
			</optgroup>
		</select>
	</form>

#searchForm = 서브밋 할 폼↑

원래 #searchForm은 검색기능을 위한 폼이지만 여기에 필요한값이 다 있어서 #searchForm을 서브밋하였다.

 

  • javascript
function fnExcelDown(){
	$('#searchForm').attr({action:"/nfeatures/retportExcelDown.do", method:'post'}).submit();
}

#searchForm을 해당 URL로 POST 서브밋 시켜주는 함수↑

 

  • controller
@RequestMapping(value = "retportExcelDown.do")
	public void retportExcelDown(@ModelAttribute ReportVO reportVO, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
		
		//엑셀 다운로드에 사용될 엑셀 폼 파일위치 정보
		String fullPath = commonProperties.getProperty("upload.file.path")+File.separator+"report_List.xlsx";//File.separator는 폴더를 하나더 생성해주는용도
		
        //데이터 조회
		List<ReportVO> reportList = reportService.selectPageReportList(reportVO);
		
		//엑셀워크북 생성을 위해 엑셀 폼파일을 FileInputStream에 담는다. 
		FileInputStream inputStream = new FileInputStream(fullPath);
		
		//워크북을 생성한다. 워크북은 엑셀파일이라고 보면 된다.
		XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
		
		//엑셀 시트 정보를 가져온다.
		XSSFSheet sheet = workbook.getSheetAt(0);
		
		//ROW 처리를 위한 변수
		XSSFRow row = null;
		
		//Cell 처리를 위한 변수
		Cell cell = null;
		
		//엑셀 내역 생성을 위한 최초 row 
		int rowIndex = 1;//<--index 번호
		
		try {
     
			//컬럼 생성시 사용될 스타일 정보를 폼 파일에서 가져 온다.
			XSSFCellStyle s0 = sheet.getRow(1).getCell(0).getCellStyle();
			XSSFCellStyle s1 = sheet.getRow(1).getCell(1).getCellStyle();
			XSSFCellStyle s2 = sheet.getRow(1).getCell(2).getCellStyle();
			XSSFCellStyle s3 = sheet.getRow(1).getCell(3).getCellStyle();
			XSSFCellStyle s4 = sheet.getRow(1).getCell(4).getCellStyle();
			
			//엑셀 컨텐츠를 생성 한다.
			int ct = 0;
			for (ReportVO vo : reportList) {
				row = sheet.createRow(rowIndex);
				ct++;
				cell = row.createCell(0);
				cell.setCellStyle(s0);
				cell.setCellValue(ct);
				
				cell = row.createCell(1);
				cell.setCellStyle(s1);
				cell.setCellValue(vo.getRegId());
				
				cell = row.createCell(2);
				cell.setCellStyle(s2);
				cell.setCellValue(vo.getReportTitle());
				
				cell = row.createCell(3);
				cell.setCellStyle(s3);
				cell.setCellValue(vo.getRegDt());
				
				cell = row.createCell(4);
				cell.setCellStyle(s4);
				cell.setCellValue(vo.getOkayYn());
				
				
				rowIndex++;
				
			}
			
			
			// 다운로드 처리를 위해 temp FileOutputStream 을 생성한다.
			// temp 파일을 만들어 놓고 생성된 파일에 
			// 위에서 작성된 workbook을 저장한다.
			FileOutputStream fs = null;
			String tempFilePath = commonProperties.getProperty("excel.form.sample.path")+File.separator+"temp"+File.separator+"tmp.xlsx";
			fs = new FileOutputStream(tempFilePath);
			workbook.write(fs);
			fs.close();
		
			
			//파일을 다운로드 하기 위한 처리
			File downLoadFile = new File(tempFilePath);
			
			int fSize = (int) downLoadFile.length();
			
			if ( fSize > 0 ) {
			    
			    BufferedInputStream in = new BufferedInputStream(new FileInputStream(downLoadFile));
			    String mimetype = "application/vnd.ms-excel; charset=UTF-8";            
			    
			    response.setBufferSize(fSize);
			    response.setContentType(mimetype);
			    String browser = request.getHeader("User-Agent");
			    //파일 인코딩
			    String downloadFileNamePrefix = "Admin_List"+".xlsx";
			    response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileNamePrefix + "\"");
			    response.setContentLength(fSize);
			    
			    FileCopyUtils.copy(in, response.getOutputStream());
			    in.close();
			    response.getOutputStream().flush();
			    response.getOutputStream().close();
			    
			    downLoadFile.delete();//어차피 샘플파일이기때문에 지워주는것.
			    
			}
			        
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			workbook.close();
		}
	}

 

String fullPath = commonProperties.getProperty("upload.file.path")+File.separator+"report_List.xlsx";

엑셀 다운로드에 사용될 엑셀(샘플) 폼 파일위치 정보 ▲

String tempFilePath = commonProperties.getProperty("excel.form.sample.path")+File.separator+"temp"+File.separator+"tmp.xlsx";

엑셀 다운로드에 사용될 엑셀(temp) 폼 파일위치 정보 ▲

 

* sample(원본)파일은 냅두고 따로 temp파일로 다운받는다.


실제로 다운받아지는것은 원래 샘플 파일이 아닌 복제된 temp파일!!

샘플 파일은 원본이라 건들지않는다.

 

엑셀파일업로드의 경우 컨트롤러에서만 프로세스를 처리해주면 되지만 엑셀파일다운로드는 

추가할것이 더 많았다.

 

 

엑셀파일 업로드는 아래링크에~!!!!!

 

2021.11.22 - [Back End/Java, Spring] - [Java/Spring] Poi 엑셀 파일 업로드(Excel _file_Upload)

 

[Java/Spring] Poi 엑셀 파일 업로드(Excel _file_Upload)

엑셀파일 업로드 jsp 엑셀파일업로드 javascript //엑셀등록 function goExcelUp(){ var formData = new FormData($('#excelUpForm')[0]); //폼데이터를 콘솔로 확인하는 방법 for (var pair of formData.entries..

zzecoding.tistory.com