quilt code

[전자정부프레임워크] 게시판 만들기 (4) 본문

weekly/게시판 만들기

[전자정부프레임워크] 게시판 만들기 (4)

김뱅쇼 2023. 12. 27. 15:17

1. excel

 

[화면]


: 엑셀 업로드/다운로드 화면 



: 다운로드 받은 엑셀에 자료의 값을 삽입/수정



:  DB에 없는 자료는 추가 되고, 바뀐 자료는 수정됨
[xml]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!-- ///////////////// excel upload 시작 /////////////////-->
 
    <update id="insertExcel" parameterType="egovframework.example.board.service.ExcelMapper">
        MERGE INTO MYEXCEL A
            USING ( SELECT      #{prodId} AS prodId
                            ,#{prodName} AS prodName
                            ,#{prodPrice} AS prodPrice
                    FROM DUAL   )
            B ON ( A.prodId = B.prodId )
            WHEN MATCHED THEN
                UPDATE 
                    SET A.prodName     = B.prodName
                        ,A.prodPrice   = B.prodPrice
            WHEN NOT MATCHED THEN
                INSERT (     prodId
                            ,prodName
                            ,prodPrice  
                        )
                VALUES  (    B.prodId
                            ,B.prodName
                            ,B.prodPrice
                        )
    
    </update>
<!-- ///////////////// excel upload 끝 /////////////////-->
cs

: merge into 쿼리 사용 

[controller]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package egovframework.example.board.controller;
 
import java.io.IOException;
 
import javax.servlet.http.HttpServletResponse;
 
import java.util.Iterator;
import org.apache.logging.log4j.core.tools.picocli.CommandLine.Help.TextTable.Cell;
import org.apache.poi.hslf.model.Sheet;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.multipart.MultipartFile;
 
import egovframework.example.board.service.ExcelServcie;
import egovframework.example.board.vo.ExcelVo;
 
 
@Controller
public class ExcelController {
 
    @Autowired
    private ExcelServcie excelService;
    
    //엑셀 등록 페이지로 이동
    @RequestMapping(value = "/excel.do")
    public String excelUpload() {
        return "board/excel";
    }
    
    //엑셀 upload
    @PostMapping(value = "/insertExcel.do", consumes = "multipart/form-data")
    public String readExcel(@RequestParam(value = "file", required=false) MultipartFile file, Model model) throws Exception { 
            
//            System.out.println("============여기까지 왔니?============");
//            System.out.println("============file: " + file);
            
            //workbook 생성(.xlsx파일)
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet worksheet = workbook.getSheetAt(0);
            
//            System.out.println("============여기까지 왔니?2============");
            
            //for문 돌려서 반복(용량이 큰 파일에는 적합하지 않음)
            for(int i=1;i<worksheet.getPhysicalNumberOfRows() ;i++) {
//                System.out.println("============엑셀 고고============");
                
                //ExcelVo 가져오기
                ExcelVo excelVo = new ExcelVo();
                DataFormatter formatter = new DataFormatter();
                
                //행 생성
                XSSFRow row = worksheet.getRow(i);
                
                //해당 컬럼에 값 넣기
                String prodId = formatter.formatCellValue(row.getCell(0));
                String prodName = formatter.formatCellValue(row.getCell(1));
                String prodPrice = formatter.formatCellValue(row.getCell(2));
                
                excelVo.setProdId(prodId);
                excelVo.setProdName(prodName);
                excelVo.setProdPrice(prodPrice);
                
                //insert 처리
                excelService.insertExcel(excelVo);
            } 
            
            return "redirect:/excel.do"
    }
    
    
    //엑셀 download
    /*
    @GetMapping(value = "/downloadExcel.do")
    public void downloadExcel(HttpServletResponse response) {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("myProd");
        Row row     = null;
        Cell cell     = null;
        int rowNum     = 0;
        
        //행 생성
        row = sheet.createRow(rowNum++);
        cell = row.createCell(0);
        cell.setCellValue("PRODID");
        
        cell = row.createCell(1);
        cell.setCellValue("PRODNAME");
        
        cell = row.createCell(2);
        cell.setCellValue("PRODPRICE");
        
        //컨텐츠 타입과 파일명 지정
        response.setContentType("ms-vnd/excel");
        response.setHeader("Content-Disposition", "attachment;filename=example.xlsx");
        
        //Excel file output
        wb.write(response.getOutputStream());
        wb.close();
    }
    */
}
 
 
 
 
 
 
 
 
 
cs



[jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title>엑셀</title>
</head>
<body>
<%@ include file="/WEB-INF/jsp/member/menu.jsp" %>
<P>엑셀 테스트 페이지</P>
 
<!-- <form action="/downloadExcel.do" method="get"> -->
    <div class="contatiner">
        <table>
            <tr>
                <td>
                    <button type="button" id="excelDownloadBtn" name="excelDownloadBtn" class="btn btn-success">EXCEL 다운로드</button>
                </td>
            </tr>
        </table>
    </div>
<!-- </form> -->
 
 
<!-- 상품 페이지 -->
 
 
 
 
 
 
<form id="excelFrm" name="excelFrm" method="POST" enctype="multipart/form-data">
    <div class="container">
        <table>
            <tr>
                <td>
                      <input type="file" name="file" class="form-control form-control-sm">
                </td>
                <td>
                      <button type="submit" class="btn btn-primary" id="excelBtn" onclick="" name="excelBtn">EXCEL 업로드</button>
                </td>
            </tr>
        </table>
    </div>
</form>
 
 
 
 
</body>
 
<script>
 
//엑셀 파일 전송
$("#excelBtn").click(function() {
   console.log("엑셀 업로드 버튼!!!!!!!!");
 
//    var data = new FormData(document.forms.namedItem("excelFrm"));
   //파일 값이 null로 보내지는 에러 배열로 보내서 해결
   var form = $("#excelFrm")[0];
   var frmData = new FormData(form);
 
   $.ajax({
      url: "<c:url value='/'/>insertExcel.do",
      data: frmData,
      type: "post",
         enctype: "multipart/form-data",
      processData: false,
      contentType: false,
      success: function(data) {
         console.log("data" + data);
         alert("EXCEL 파일 업로드 완료");
      },
      error: function(e) {
          alert("error");
      }
   });
})
 
 
//엑셀 파일 다운로드
$('#excelDownloadBtn').on( 'click'function() {
    document.location.href = "/excel/PROD_example.xlsx";
})
    
</script>
 
</html>
 
 
cs


 

 

2. chart

[화면]





[jsp]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<%@page import="egovframework.example.board.vo.CmntVo"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>차트</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-..." crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="mb-3" style=" width: 700px; height: 1000px;"> 
    <canvas id="myChart" width="400" height="400"></canvas>
</div>
</body>
<script>
$(document).ready(function(){ 
   getGraph();
});
 
function getGraph(){
     var dateList = [];
     var countList = [];
     
     console.log("차트 왔당!!");
      
     $.ajax({
        url: "<c:url value='/'/>chartAjax.do",
        contentType: "application/json; charset=UTF-8",
        type: "get",
        dataType: "json",
        success: function(data){
           console.log("ajax 성공");
//            console.log("얍: " + data);
//            console.log("얍얍: " + data[0]);
           
           for (var i = 0; i < data.length; i++) {
//               console.log("얍얍얍: " + data[i]);
           }
           
           // 그래프로 나타낼 자료 리스트에 담기
           for (var i = 0; i < data.length; i++){  
              dateList.push(data[i].reDate);
              countList.push(data[i].recount);
           }
           
           // 그래프
           new Chart(document.getElementById("myChart"), {
               type: 'line',
               data: {
                 labels: dateList, // X축 
                 datasets: [{ 
                     data: countList, // 값
                     label: "날짜별 댓글수",
                     borderColor: 'rgba(255, 99, 132, 1)',
                     fill: false
                   }
                 ]
               },
               options: {
                 title: {
                   display: true,
                   text: '게시글 댓글 수'
                 }
               }
             }); //그래프
        },
        error: function(){
           alert("실패");
        }  
     }); // ajax     
}
 
 
 
 
</script>
 
 
 
</html>
cs