째의 개발 기록방

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

Back End/Java, Spring

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

째린이 2021. 11. 22. 16:48

엑셀파일 업로드/다운로드 될 화면단

엑셀파일 업로드

 

  • jsp
<form name="excelUpForm" id="excelUpForm" enctype="multipart/form-data" method="POST">
  <input type="file" id="excelFile" name="excleFile" value="" style="display: inline-block; margin: 0 10px 0 0; float: left;"/>
  <a href="javascript:goExcelUp()" class="button" style="width: 140px">엑셀파일업로드</a>
</form>

 

 

  • javascript
//엑셀등록
	function goExcelUp(){
		var formData = new FormData($('#excelUpForm')[0]);
		
		//폼데이터를 콘솔로 확인하는 방법
		for (var pair of formData.entries()) {
			console.log(pair[0]+ ', ' + pair[1]);
		}
		
		var url = "/reportExcelUpload.do";
		
		if(confirm("엑셀 파일을 등록하시겠습니까?")){
			$.ajax({
				url : url,
				type: "post",
				data: formData,
				enctype: "multipart/form-data",
				processData: false,
				contentType: false,
				cache: false,
				error: function(error){
					alert("Error!");
				},
				success: function(data){
						console.log(">>>>>>>>>>>>>>"+data);
						alert("등록 완료!");
						location.reload();
						return;
					
				}
			});
		}
	}

 

ajax FormData로 서버에 보내기!

 

 

  • controller
@ResponseBody
	@RequestMapping(value="/reportExcelUpload.do", method = RequestMethod.POST)
	public ModelAndView reportExcelUpload(MultipartHttpServletRequest file,@ModelAttribute ReportVO reportVO, HttpServletRequest request) throws Exception {
	
		ModelAndView mv = new ModelAndView("jsonView");
		MultipartFile mf = file.getFile("excleFile");
		int result = 0;
		XSSFWorkbook workbook = null;
		try {
			if(file != null && file.getFile("excleFile") != null && !file.getFile("excleFile").isEmpty()) {
				
				String folderPath = commonProperties.getProperty("upload.file.path") + File.separator + "excelUpload" + File.separator;
				
				String fullPath = folderPath + NfDateUtil.getDate("yyyyMMddHHmmss") + ".xlsx";
				
				File existsDir = new File(folderPath);
				
				if (!existsDir.exists()) {
					existsDir.mkdir();
				}else{			
					logger.debug("folder exists!!");
				}
				
				File saveFile = new File(fullPath);
				mf.transferTo(saveFile);
			
				
				FileInputStream inputStream = new FileInputStream(fullPath);
                
				workbook = new XSSFWorkbook(inputStream);
                
				XSSFSheet sheet = workbook.getSheetAt(0);
				
				//ROW 처리를 위한 변수
			    XSSFRow row = null;
			    //Cell 처리를 위한 변수
			    Cell cell = null;
				
			    
			    List<ReportVO> reportList = new ArrayList<ReportVO>();
			    
				ReportVO rowData = null;
			    for(int rowIndex = 1; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
			    	//ReportVO rowData = new ReportVO();
			    	rowData = new ReportVO();
			    	
			    	row = sheet.getRow(rowIndex);
                    
			    	//번호
			    	//rowData.setReportId(reportId);
			    	//작성자
			    	rowData.setRegId(row.getCell(0).toString());
			    	//제목
			    	rowData.setReportTitle(row.getCell(1).toString());
			    	//작성일
			    	rowData.setRegDt(row.getCell(2).getDateCellValue());
			    	//승인여부
			    	rowData.setOkayYn(row.getCell(3).toString());
                    //내용
			    	rowData.setReportContent(row.getCell(4).toString());
                    //시작일
			    	rowData.setStartDate(row.getCell(5).toString());
                    //종료일
			    	rowData.setEndDate(row.getCell(6).toString());
			    	reportList.add(rowData);
			    }
			    result = reportService.insertReportList(reportList);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			workbook.close();
		}
		
		mv.addObject("excelUp", result );
		return mv;
	}

commonProperties.getProperty("upload.file.path")  <-- 프로퍼티에 설정되어있는 경로의 값을 적어준다.

 

엑셀파일업로드의 경우 sample 엑셀파일을 만들어두고 시작을한다.

이때 등록폼과 똑같은 구성으로 만들어야하며 초반에 엑셀 스타일을 정해두어야한다!

 

1. 엑셀파일을 특정위치에 저장한다.

2. 저장 된 파일을 워크북에 담는다. (시트, 로우, 셀)

3. 리스트를 새로 생성하여 담아준다.

4. 저장처리한다.

 

List<ReportVO> reportList = new ArrayList<ReportVO>();

//NULL처리를 진행해주고 포문을 돌려야 메모리를 잡아먹지않는다.
ReportVO rowData = null;

for(int rowIndex = 1; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
  //그때그때 생성되서 메모리를 차지하게된다.
  //ReportVO rowData = new ReportVO();

* 이때 저장처리 과정에서 for문을 돌릴때 for문 바깥에 vo를 비워준다.

그렇지않고 for문안에 새로이 생성자를 사용해서 할 경우 루프가 돌때마다 그때그때 생성되어

메모리를 차지하기 때문이다.

 

 

엑셀 다운로드는 아래링크 참조!!

2021.11.18 - [Back End/Java, Spring] - [Java/Spring] Poi 엑셀 파일 다운로드(Excel _file_Download)

 

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

지금 개발 진행(연습) 중인 CRUD 엑셀파일다운로드 = 현재 화면에 뿌려져있는 데이터를 엑셀파일로 받겠다. 엑셀파일업로드 = 샘플로 제공된 엑셀파일로 데이터를 가공하여 업로드 시키겠다. 엑

zzecoding.tistory.com