myname 2025-03-07
2025-03-07 16:50 결제관리 excel download 수정
@4fe717d4ef4ff181a05f7f24200f5f3910445b4e
src/main/java/itn/let/mjo/pay/web/MjonPayController.java
--- src/main/java/itn/let/mjo/pay/web/MjonPayController.java
+++ src/main/java/itn/let/mjo/pay/web/MjonPayController.java
@@ -13,11 +13,9 @@
 import java.text.NumberFormat;
 import java.text.SimpleDateFormat;
 import java.time.LocalDate;
-import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -41,18 +39,12 @@
 import org.json.simple.parser.JSONParser;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.ui.ModelMap;
 import org.springframework.web.bind.annotation.ModelAttribute;
-import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.multipart.MultipartHttpServletRequest;
 import org.springframework.web.servlet.HandlerMapping;
@@ -67,7 +59,6 @@
 import itn.com.cmm.ComDefaultCodeVO;
 import itn.com.cmm.EgovMessageSource;
 import itn.com.cmm.LoginVO;
-import itn.com.cmm.RestResponse;
 import itn.com.cmm.service.EgovCmmUseService;
 import itn.com.cmm.service.FileVO;
 import itn.com.cmm.util.DateUtils;
@@ -76,8 +67,6 @@
 import itn.com.cmm.util.RedirectUrlMaker;
 import itn.com.cmm.util.StringUtil;
 import itn.com.utl.fcc.service.EgovStringUtil;
-import itn.let.fax.admin.service.FaxStatVO;
-import itn.let.mail.service.StatusResponse;
 import itn.let.mjo.mjocommon.MjonCommon;
 import itn.let.mjo.msg.service.MjonMsgService;
 import itn.let.mjo.msg.service.MjonMsgVO;
@@ -107,6 +96,7 @@
 import itn.let.uss.umt.service.MberManageVO;
 import itn.let.uss.umt.service.UserManageVO;
 import itn.let.utl.fcc.service.EgovCryptoUtil;
+import itn.let.utl.user.service.ExcelUtil;
 import itn.let.utl.user.service.MjonNoticeSendUtil;
 
 @Controller
@@ -1952,7 +1942,6 @@
 		
 		model.addAttribute("prePaymentYn", userManageVO.getPrePaymentYn());
     	
-		
 		System.out.println("pattern :: "+ pattern);
     	if(pattern.equals("/web/member/pay/PayListAllAjax.do")
     			|| pattern.equals("/web/member/pay/PayListMobileAjax.do")
@@ -2051,7 +2040,7 @@
             	
     			return "/web/pay/PayListRefundAjax";
     		}
-        	
+
         	//일반 결제 페이지 처리
     		if("".equals(mjonPayVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
     			mjonPayVO.setSearchSortCnd("moid");
@@ -2073,7 +2062,7 @@
     			}
     			
     		}
-    		
+	
 			if(pattern.equals("/web/member/pay/PayListAllAjax.do")) { //전체
     			mjonPayVO.setPageType("all");
     		}
@@ -2121,7 +2110,7 @@
         	
 //			mjonPayVO.setStartDate(mjonPayVO.getStartDate() == null ? DateUtil.getDateDaysAgo(365) : mjonPayVO.getStartDate());
 //			mjonPayVO.setEndDate(mjonPayVO.getEndDate() == null ? DateUtil.getCurrentDate() : mjonPayVO.getEndDate());
-			
+
 			if(!DateUtils.dateChkAndValueChk(mjonPayVO.getStartDate(),mjonPayVO.getEndDate(), 12 )) {
 				mjonPayVO.setStartDate(DateUtils.getDateMonthsAgo(12));
 				mjonPayVO.setEndDate(DateUtils.getCurrentDate());
@@ -4085,7 +4074,7 @@
 	}
     
     //결제 엑셀 다운로드 
-    @RequestMapping(value= {"/web/member/pay/PayExcelDownload.do"})
+    @RequestMapping(value= {"/web/member/pay/PayExcelDownload_OLD.do"})
   	public void PayExcelDownload( MjonPayVO mjonPayVO, 
 			HttpServletRequest request,
 			HttpServletResponse response ,
@@ -4180,6 +4169,118 @@
   		}
   	}
     
+    //결제 엑셀 다운로드 
+    @RequestMapping(value= {"/web/member/pay/PayExcelDownload.do"})
+  	public void PayNewExcelDownload( MjonPayVO mjonPayVO, 
+			HttpServletRequest request,
+			HttpServletResponse response ,
+			ModelMap model) throws Exception {
+    	
+    	//로그인 여부 체크 및 ID 획득
+    	LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
+		String userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
+		if(loginVO != null) {
+
+			String fileName ="결제내역 엑셀 리스트";	//file name
+	  		
+	  		try{
+	  			/** pageing */
+	    		PaginationInfo paginationInfo = new PaginationInfo();
+	    		paginationInfo.setCurrentPageNo(1);
+	    		paginationInfo.setRecordCountPerPage(10000);
+	    		paginationInfo.setPageSize(10);
+	    		
+	    		mjonPayVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
+	    		mjonPayVO.setLastIndex(paginationInfo.getLastRecordIndex());
+	    		mjonPayVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
+	    		
+	    		mjonPayVO.setUserId(userId);
+	    		
+	    		
+	    		//url에 따른 타입 처리
+	    		String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
+	    		System.out.println("pattern========");
+	    		System.out.println(pattern);
+	    		
+	    		//url에 따른 검색 조건 처리
+	    		mjonPayVO = this.p_checkSearchCnd(pattern, mjonPayVO);    		 
+
+	    		
+	    		//검색 기간 처리
+	    		mjonPayVO = this.p_checkSearchDate(mjonPayVO);
+	    		
+				
+	        	//정렬 처리
+	    		mjonPayVO = this.p_checkSortCnd(mjonPayVO); 
+	    		
+	    		
+	    		//결과 리스트 정보 불러오기
+	            List<MjonPayVO> resultList = mjonPayService.selectPayList(mjonPayVO);   
+	            
+	  			//필요 컬럼 추가 
+	  			for (int i=0;i<resultList.size();i++) {
+	  				MjonPayVO tMjonPayVO = resultList.get(i);
+	  				tMjonPayVO.setSeqNo(resultList.size()-i);
+	  			}
+	  			
+	  			//excel 만들기
+	  			List<Object> excelData  = new ArrayList<>();
+				excelData.addAll(resultList);
+				// 세팅값
+				String title = "요금결제내역";	//sheet name & title
+				
+				// 너비
+				int[] width = {
+						4000
+						, 4000
+						, 4000
+						, 4000					
+						, 4000
+						
+						, 4000
+						//, 4000
+						, 4000
+				};
+
+				// 헤더
+				String[] header = {
+						"번호"
+						, "결제일시"
+						, "결제방식"
+						, "결제금액"
+						, "충전금액"
+						
+						, "결제상태"
+						//, "증빙서류 발행 요청"
+						, "비고1"
+				};
+				
+				// 컬럼명
+				String[] order = {
+						"SeqNo"
+						, "RegDate"
+						, "PayMethodTxt"
+						, "Amt"
+						, "Cash"
+						
+						, "PgStatusTxt"
+						//, "RcptTypeTxt"
+						, "VbankNum"												
+						
+				};
+
+				// 호출 - download file 처리
+				SXSSFWorkbook workbook = ExcelUtil.makeSimpleFruitExcelWorkbook(excelData , header, order, width, title);				
+				response = this.p_makeResponse(response, fileName);				
+		  		workbook.write(response.getOutputStream());
+	  	    
+	  		}catch(Exception e) {
+	  			e.printStackTrace();  			
+	  		}
+        	
+		}  		
+		
+  	}
     
     //포인트 교환내역 엑셀 다운로드 
     @RequestMapping(value= {"/web/member/pay/PointExcelDownload.do"})
@@ -6088,6 +6189,119 @@
 		model.addAttribute("paginationInfo", paginationInfo);
 		
 		return "/uss/ion/pay/cashPointSendList";
-    }    
+    }
+    
+    /**
+     * @param p_pattern
+     * @param p_mjonPayVO
+     * @return
+     * @throws Exception
+     */
+    private MjonPayVO p_checkSearchCnd(
+    		String p_pattern
+    		, MjonPayVO p_mjonPayVO
+    		) throws Exception{
+    	if(p_pattern.equals("/web/member/pay/PayListAllAjax.do")) { //전체
+			p_mjonPayVO.setPageType("all");
+		}
+		if(p_pattern.equals("/web/member/pay/PayListMobileAjax.do")) { //모바일일때
+			p_mjonPayVO.setSearchCondition2("CELLPHONE");
+			p_mjonPayVO.setPayMethod("CELLPHONE");
+			p_mjonPayVO.setPageType("cellphone");
+		}
+		if(p_pattern.equals("/web/member/pay/PayListCardAjax.do")) { //신용카드
+			p_mjonPayVO.setSearchCondition2("CARD");
+			p_mjonPayVO.setPayMethod("CARD");
+			p_mjonPayVO.setPageType("card");
+		}
+		if(p_pattern.equals("/web/member/pay/PayListVBankAjax.do")) { //전용계좌
+			p_mjonPayVO.setSearchCondition2("VBANK");
+			p_mjonPayVO.setPayMethod("VBANK");
+			p_mjonPayVO.setPageType("vbank");
+		}
+		if(p_pattern.equals("/web/member/pay/PayListBankAjax.do")) { //즉시이체
+			p_mjonPayVO.setSearchCondition2("BANK");
+			p_mjonPayVO.setPayMethod("BANK");
+			p_mjonPayVO.setPageType("bank");
+		}    		
+		if(p_pattern.equals("/web/member/pay/PayListSPayAjax.do")) { //즉시이체
+			p_mjonPayVO.setSearchCondition2("SPAY");
+			p_mjonPayVO.setPayMethod("SPAY");
+			p_mjonPayVO.setPageType("SPAY");
+		}    		    		
+		if(p_pattern.equals("/web/member/pay/PayListOfflineAjax.do")) { //무통장
+			p_mjonPayVO.setSearchCondition2("OFFLINE");
+			p_mjonPayVO.setPayMethod("OFFLINE");
+			p_mjonPayVO.setPageType("offline");
+		}   
+		
+		return p_mjonPayVO;
+    }
+    
+    /**
+     * @param p_mjonPayVO
+     * @return
+     * @throws Exception
+     */
+    private MjonPayVO p_checkSortCnd(
+    		MjonPayVO p_mjonPayVO
+    		) throws Exception{
+    	//정렬 처리
+		if("".equals(p_mjonPayVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
+			p_mjonPayVO.setSearchSortCnd("moid");
+			p_mjonPayVO.setSearchSortOrd("desc");
+		}else {//포인트 교환내역에서 정렬 종류가 달라서 변환처리 해줌
+			
+			String sortCnt = p_mjonPayVO.getSearchSortCnd();
+			
+			if(sortCnt.equals("pointUseId") || sortCnt.equals("refundId")) {
+				p_mjonPayVO.setSearchSortCnd("moid");
+			}else if(sortCnt.equals("frstRegistPnttm") || sortCnt.equals("frstRegisterPnttm") || sortCnt.equals("refundHandlePnttm")) {
+				p_mjonPayVO.setSearchSortCnd("regDate");
+			}else if(sortCnt.equals("type")) {
+				p_mjonPayVO.setSearchSortCnd("payMethodTxt");
+			}else if(sortCnt.equals("point") || sortCnt.equals("refundMoney") || sortCnt.equals("refundCash")) {
+				p_mjonPayVO.setSearchSortCnd("amt");
+			}else if(sortCnt.equals("cmpltYn") || sortCnt.equals("refundStatus")) {
+				p_mjonPayVO.setSearchSortCnd("pgStatusTxt");
+			}
+			
+		}
+		
+		return p_mjonPayVO;
+    }
+    
+    /**
+     * @param p_mjonPayVO
+     * @return
+     * @throws Exception
+     */
+    private MjonPayVO p_checkSearchDate(
+    		MjonPayVO p_mjonPayVO
+    		) throws Exception{
+    	//검색 기간 처리
+		if(!DateUtils.dateChkAndValueChk(p_mjonPayVO.getStartDate(),p_mjonPayVO.getEndDate(), 12 )) 
+		{
+			p_mjonPayVO.setStartDate(DateUtils.getDateMonthsAgo(12));
+			p_mjonPayVO.setEndDate(DateUtils.getCurrentDate());
+		}
+		
+		return p_mjonPayVO;
+    }
+    
+    private HttpServletResponse p_makeResponse(
+    		HttpServletResponse p_response
+    		, String p_fileName
+    		) throws Exception{
+    	p_response.setHeader("Set-Cookie", "fileDownload=true; path=/");
+  		SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ( "yyyy_MM_dd_HH_mm_ss", Locale.KOREA );
+  		Date currentTime = new Date ();
+  		String mTime = mSimpleDateFormat.format ( currentTime );
+  		p_fileName = p_fileName+"("+mTime+")";
+  		
+  		p_response.setHeader("Content-Disposition", String.format("attachment; filename=\""+new String((p_fileName).getBytes("KSC5601"),"8859_1")+".xlsx"));
+  		
+  		return p_response;
+    }
 }
 
 
src/main/java/itn/let/utl/user/service/ExcelUtil.java (added)
+++ src/main/java/itn/let/utl/user/service/ExcelUtil.java
@@ -0,0 +1,143 @@
+package itn.let.utl.user.service;
+
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.Method;
+import java.util.List;
+
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFDataFormat;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.VerticalAlignment;
+import org.apache.poi.xssf.streaming.SXSSFSheet;
+import org.apache.poi.xssf.streaming.SXSSFWorkbook;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ExcelUtil {
+    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
+
+    /**
+     * 엑셀 파일을 방출합니다.
+     *
+     * @param voList 엑셀에 넣고 싶은 vo 리스트 형태로 넣습니다.
+     * @param header 엑셀 해더
+     * @param order 헤더에 해당하는 내용의 vo 필드 이름을 작성합니다. 예를 들어 String userName; 필드의 1번째 해더이름을 "사용자 이름" 으로 정했으면
+     *        순서를 맞추어 1번째 order 배열에 "UserName" 이라는 글짜를 입력해줍니다(*주의:첫 문자는 대문자, 낙타체). 첫번째 컬럼에는 "줄번호"가
+     *        들어가는데, 이것에 대한 내용은 order에 값을 입력하지 않습니다.
+     * @param width 컬럼 너비를 설정합니다. length가 해더의 length와 일치할 필요는 없습니다.
+     * @param title
+     * @throws Exception
+     * @return SXSSFSheet
+     *
+     *         특징 : 해더보다 내용의 컬럼수가 많을 때 해당 줄의 컬럼은 cut, 해더 이름이 vo와 다르게 되면 해당 컬럼 출력 안됨 require : 날짜 포멧은
+     *         지원하지 않습니다.
+     *
+     *
+     *         ***********************************************************************************************
+     *         EX String title = "게시판 리스트";
+     *         int[] width = {1500, 1500, 1500, 3000, 30000, 3000 };
+     *         String[] header = {"번호", "게시판번호", "작성자", "제목", "내용", "작성일" }; 
+     *         String[] order = { "Seq", "UserId", "Title", "Content", "RegDt" }; 
+     *         => 첫번째 "번호"에 대한 order 이름이 비어있습니다.
+     *
+     *         ***********************************************************************************************
+     */
+    public static SXSSFWorkbook makeSimpleFruitExcelWorkbook(List<Object> voList, String[] header, String[] order, int[] width, String title) throws Exception {
+    	// 시트 생성
+    	SXSSFWorkbook workbook = new SXSSFWorkbook();
+    	SXSSFSheet sheet = workbook.createSheet(title);
+		for (int i = 0; i < width.length; i++) {
+			// JSP 2022.02.24 => width 변경
+			//sheet.setColumnWidth(0, width[width.length - (i + 1)]);
+			sheet.setColumnWidth(i, width[i]);
+		}
+
+		int r = 2;// 줄부터 찍기
+		
+		CellStyle headerstyle = workbook.createCellStyle();
+		headerstyle.setAlignment(HorizontalAlignment.CENTER);
+		headerstyle.setVerticalAlignment(VerticalAlignment.CENTER);
+		headerstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
+        // 헤더 행 생
+        Row headerRow = sheet.createRow(r);
+        // 해더 값 채움 (우측 방향으로)
+        Cell headerCell = null;
+        for (int i = 0; i < header.length; i++) {
+        	headerRow.setHeight((short)512);
+        	
+            headerCell = headerRow.createCell(i);
+            headerCell.setCellStyle(headerstyle);
+            headerCell.setCellValue(header[i]);
+        }
+
+        // 내용 행 및 셀 생성
+		Row bodyRow = null;
+		Cell bodyCell = null;
+
+        bodyRow = sheet.createRow(0);
+        bodyCell = bodyRow.createCell(0);
+        bodyCell.setCellValue(title);// 읽어온 데이터 표시
+
+        //System.out.println("voList.size()");
+        //System.out.println(voList.size());
+        //System.out.println(voList.size());
+        
+        int c = 0;// 컬럼
+        for (Object vo : voList) {
+            bodyRow = sheet.createRow(r + 1);
+            bodyCell = bodyRow.createCell(0);
+            //bodyCell.setCellValue(r + 1); // 첫 컬럼은 줄 번호
+
+            PropertyDescriptor pd; // 클래스의 필드 메소드를 찾아줌. 이름을 기존에 vo.setUserId() 란 메소드를 통해서만 호출이 가능 했다면, PropertyDescriptor는 이름만으로 메소드
+                                   // 호출이 가능함. 클래스가 변경 되어도 동일한 작동으로 getter&setter 호출이 가능하도록 도와줌
+            Method[] methods = vo.getClass().getDeclaredMethods(); // 메소드들 호출함
+            // 배열로 준 이름 과 같으면 해당 열 데이터 쓰기
+            for (int i = 0; i < order.length; i++) {
+                for (Method method : methods) { // vo 내부 메소드 반복
+
+//                	System.out.println("i :: "+ i + "methods : "+ methods);
+                	/*System.out.println("voList.method()");
+                    System.out.println(method.getName());*/
+                    
+                    if (method.getName().equals("get" + (order[i] == null ? "" : order[i]))) { // vo메소드 이름과 order의 이름 비교
+                        // getter 호출 준비
+                        String getMethodName = method.getName().substring(3); // getter의 이름 가져옴
+                        pd = new PropertyDescriptor(getMethodName, vo.getClass());
+                        // vo의 데이터 세팅
+                        String cellData = (pd.getReadMethod().invoke(vo) != null ? pd.getReadMethod().invoke(vo) : "").toString();
+                        bodyCell = bodyRow.createCell(c++); // 데이터 순서
+                        if(getMethodName.equals("InstrFee") || getMethodName.equals("SpecialWorkAllow") || getMethodName.equals("DistanceAllow")
+                        	|| getMethodName.equals("TrafficFee") || getMethodName.equals("AcmdtFee")
+                        	|| getMethodName.equals("Amt") || getMethodName.equals("Cash")
+                        	){
+                        	
+                        	// JSP 2022.02.22 => null 에러 try~catch 문 추가
+                        	try {
+                            	double num = Double.parseDouble(cellData);
+                            	CellStyle bodyStyle = workbook.createCellStyle();
+                            	bodyCell.setCellValue(num);// 읽어온 데이터 표시
+                            	bodyStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));
+                            	bodyCell.setCellStyle(bodyStyle);
+                        	}
+                        	catch (Exception ex) {
+                        		bodyCell.setCellValue(cellData);
+                        	}                        	
+                        }else {
+                        	bodyCell.setCellValue(cellData);// 읽어온 데이터 표시	
+                        }
+                        //System.out.println("@@  :  "+getMethodName  +"       ---           " + cellData);
+                    }
+                }
+            }
+            c = 0;
+            r++;
+        }
+        return workbook;
+    }
+
+}
Add a comment
List