SpringMVC Excel 가져오기

4490 단어 JavaWeb-Spring
1. 의존 추가

	org.apache.poi
	poi-ooxml
	3.5-FINAL

2. Ajax가 업로드한 excel의 기능 구현
function upload() {
		var uploadResult = document.getElementById("upload-result");
		uploadResult.style.color = "green";
		uploadResult.innerHTML = " .....";
		var formData = new FormData($("uploadForm")[0]);
		formData.append('Content-Type', 'multipart/form-data');
		formData.append('image', $('input[type=file]')[0].files[0]);
		$.ajax({
			url : "${pageContext.request.contextPath}/api/v1/file",
			type : 'POST',
			data : formData,
			dataType : 'json',
			contentType : false,
			processData : false,
			cache : false,// 
			error : function(data) {
				alert(" , ")
				console.log(data);
			},
			success : function(data) {
				console.log(data);
				var code = data.status;
				if (code == 200) {
					uploadResult.style.color = "green";
					uploadResult.innerHTML = " ";
					imgUrl = data.id;
				} else {
					uploadResult.style.color = "red";
					uploadResult.innerHTML = " ";
				}
			}

		});
	}

3. 파일 처리를 위한 SpringMVC controller
 public static List getExcelDataFromReqeust(HttpServletRequest request,BaseBean baseBean) {
			List resultList = new ArrayList<>();
			List> result = null;
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			//  request multipart ,
			if (multipartResolver.isMultipart(request)) {
				//  request multipart 
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile((String) iter.next());
					if (file != null) {
						try {
							result = ExcelImportUtil.parseExcel(file.getInputStream());
							for (Map map : result) {
								BaseBean newBean = (BaseBean) baseBean.clone();
								transMap2Bean2(map,newBean);
								resultList.add(newBean);
							}
						} catch (IllegalStateException | IOException e) {
							e.printStackTrace();
						}
					}
				}
				return resultList;
			} else {
				return resultList;
			}
		}
	 
		
	    public static void transMap2Bean2(Map map, Object obj) {  
	        if (map == null || obj == null) {  
	            return;  
	        }  
	        try {  
	            BeanUtils.populate(obj, map);  
	        } catch (Exception e) {  
	            System.out.println("transMap2Bean2 Error " + e);  
	        }  
	    }  

3.1 도구 클래스 분석 excel 데이터
 public static List> parseExcel(InputStream fis) {  
	        List> data = new ArrayList>();;  
	        try {  
	            HSSFWorkbook book = new HSSFWorkbook(fis);  
	            HSSFSheet sheet = book.getSheetAt(0);  
	            int firstRow = sheet.getFirstRowNum();  
	            int lastRow = sheet.getLastRowNum();
	            //   
	            for(int i = firstRow + 1; i map = new HashMap();  
	                  
	                HSSFRow row = sheet.getRow(i);  
	                int firstCell = row.getFirstCellNum();  
	                int lastCell = row.getLastCellNum();  
	                  
	                for(int j=firstCell; j

4. 호출하는 방법
	@RequestMapping(value = "/excel", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadFile(HttpServletRequest request) {
		List result = ExcelImportUtil.getExcelDataFromReqeust(request,new VaccineItem());
		for (BaseBean object : result) {
			VaccineItem vaccineItem = (VaccineItem) object;
			System.out.println(vaccineItem.toString());
		}
		return StatusConfig.OK;
	}

좋은 웹페이지 즐겨찾기