springboot+idea+bootstrap實現批量導入操作

最近在做bootstrap的項目,遇到過一些問題,但是在網上找的東西總不是很全面,但是項目還是要做的,所有就自己一邊網上找,一邊自己琢磨,現在整理了一下 希望你們能看懂。謝謝

1.先導入js哦,定義一個button

        <script type="application/javascript" src="/lib/js/jquery-3.1.1.js"></script>
        <script type="application/javascript" src="/lib/js/fileinput.js"></script>
    <script type="text/javascript"
            src="/lib/js/zh.js"></script>
<div class="alarm">
            <button class="btn btn-primary" id="upload">批量導入</button>
        </div>

2.創建批量導入模態框


<!--批量導入操作-->
<!-- 模態框(Modal) -->

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">文件上傳</h4>
            </div>
            <div class="modal-body">
                <input id="f_upload" type="file"  name="file"/>
            </div>
         
        </div>
    </div>
</div>

3.js代碼

<script>
    $(function(){

        initUpload();

        $("#upload").on("click",function(){
        //店家批量導入按鈕 顯示模態框
            $("#myModal").modal("show");
        });

    })
    function initUpload(){
        $("#f_upload").fileinput({
            language: 'zh',//設置語言
            uploadUrl: "/eaxmManager/eaxm/importExam",//上傳的地址
            allowedFileExtensions: ["xls", "xlsx"],//接收的文件後綴
            dropZoneTitle: '可以將文件拖放到這裏',
            uploadAsync: true, //默認異步上傳
            showPreview: true,//是否顯示預覽
            showUpload: true,//是否顯示上傳按鈕
            showRemove: true, //顯示移除按鈕
            showCancel:true,   //是否顯示文件上傳取消按鈕。默認爲true。只有在AJAX上傳過程中,纔會啓用和顯示
            showCaption: true,//是否顯示文件標題,默認爲true
            browseClass: "btn btn-primary", //文件選擇器/瀏覽按鈕的CSS類。默認爲btn btn-primary
            dropZoneEnabled: true,//是否顯示拖拽區域
            maxFileSize: 0,//最大上傳文件數限制,單位爲kb,如果爲0表示不限制文件大小
            minFileCount: 1, //每次上傳允許的最少文件數。如果設置爲0,則表示文件數是可選的。默認爲0
            maxFileCount: 1, //每次上傳允許的最大文件數。如果設置爲0,則表示允許的文件數是無限制的。默認爲0
            previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",//當檢測到用於預覽的不可讀文件類型時,將在每個預覽文件縮略圖中顯示的圖標。默認爲<i class="glyphicon glyphicon-file"></i>
            previewFileIconSettings: {
                'docx': '<i ass="fa fa-file-word-o text-primary"></i>',
                'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'jpg': '<i class="fa fa-file-photo-o text-warning"></i>',
                'pdf': '<i class="fa fa-file-archive-o text-muted"></i>',
                'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
            },
            msgFilesTooMany: "選擇上傳的文件數量({n}) 超過允許的最大數值{m}!",//字符串,當文件數超過設置的最大計數時顯示的消息 maxFileCount。默認爲:選擇上傳的文件數({n})超出了允許的最大限制{m}。請重試您的上傳!
            elErrorContainer: '#kartik-file-errors'
        }).on("fileuploaded", function(event, data, previewId, index) {
       		 //導入成功後 隱藏模態框,我這是隱藏所有的模態框
            $(".modal").modal("hide");
            //導入成功夠刷新當前table 根據自己項目改$("#examTable") 即可
            $("#examTable").bootstrapTable('refresh');
            console.log("fileuploaded");
            console.log("event"+event);
            console.log("data"+data);
            console.log("previewId"+previewId);
            console.log("index"+index);
        }).on('fileerror', function(event, data, msg) {
            console.log("fileerror");
            console.log("event"+event);
            console.log("data"+data);
            console.log("msg"+msg);
        });
    }
</script>

4.點擊批量導入按鈕,顯示模態框如下圖,點擊選擇導入excel,點擊上傳即可

打開批量導入模態框

5.serviceImpl層,相關的註釋寫的很清楚注意看下面(注意下面是在第幾個單元格開始讀取)


    @Override
    public int insertExam(MultipartFile file) throws Exception {
        int result = 0;
        //存放excel表中所有user數據
        List<EaxmDTO> eaxmList = new ArrayList<>();

        //file.getOriginalFilename()方法 得到上傳時的文件名
        String fileName = file.getOriginalFilename();
        //截取文件名的後綴
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);

        //file.getInputStream()方法  返回InputStream對象 讀取文件的內容
        InputStream ins = file.getInputStream();
        Workbook wb = null;
        /*判斷文件後綴
            XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
            HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。*/
        if(suffix.equals("xlsx")){
            wb = new XSSFWorkbook(ins);
        }else{
            wb = new HSSFWorkbook(ins);
        }

        //獲取excel表單的sheet對象
        Sheet sheet = wb.getSheetAt(0);
        //如果sheet不爲空,就開始遍歷表中的數據
        if(null != sheet){
           //line = 1 :從表的第2行開始獲取記錄
            for(int line = 1; line <= sheet.getLastRowNum();line++){

                //excel表單的sheet的行對象
                Row row = sheet.getRow(line);

                //如果某行爲空,跳出本行
                if(null == row){
                    continue;
                }
                //獲取第一個單元格的內容
                //表示獲取單元格中的內容是String字符串類型
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
               String examti = row.getCell(0).getStringCellValue();
               //這解決的是單元格內讀取的日期是天(寫的是年月日,但是讀取後變成了總天數),需要休眠操作在轉換成年月日格式
                Calendar calendar = new GregorianCalendar(1900,0,-1);
                Date d = calendar.getTime();
                Date examtime = DateUtils.addDays(d,Integer.valueOf(examti);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String timeFormat = sdf.format(examtime);

            
                //獲取第二個單元格的內容
                //格式是number
                Double sbp = row.getCell(1).getNumericCellValue();
                //獲取第三個單元格的內容
                Double dbp = row.getCell(2).getNumericCellValue();

                Double bmi = row.getCell(3).getNumericCellValue();

                Double whr = row.getCell(4).getNumericCellValue();

                Double bun = row.getCell(5).getNumericCellValue();

                Double ua = row.getCell(6).getNumericCellValue();

                Double crea = row.getCell(7).getNumericCellValue();

                Double tg = row.getCell(8).getNumericCellValue();

                Double chol = row.getCell(9).getNumericCellValue();

                Double glu = row.getCell(10).getNumericCellValue();

                Double hcy = row.getCell(11).getNumericCellValue();

                Double mAlb = row.getCell(12).getNumericCellValue();

                Double MalbCrea = row.getCell(13).getNumericCellValue();

                double teacherid = row.getCell(14).getNumericCellValue();

                EaxmDTO eaxm = new EaxmDTO();

                eaxm.setExamtime(timeFormat);
                eaxm.setSbp(sbp);
                eaxm.setDbp(dbp);
                eaxm.setBmi(bmi);
                eaxm.setWhr(whr);
                eaxm.setBun(bun);
                eaxm.setUa(ua);
                eaxm.setCrea(crea);
                eaxm.setTg(tg);
                eaxm.setChol(chol);
                eaxm.setGlu(glu);
                eaxm.setHcy(hcy);
                eaxm.setmAlb(mAlb);
                eaxm.setmAlbCrea(MalbCrea);
                eaxm.setTeacherid(teacherid);
                eaxmList.add(eaxm);

            }
            //這其實可以在做一下 判斷  是否數據庫裏已經存在了你要導入數據,我麼得寫,不想寫,懶,難受
            for(EaxmDTO eaxm:eaxmList){
                    result = eaxmMapper.insertEaxm(eaxm);
            }
        }
        return result;


    }

6.controller層如下

 /**
     * 導入excel
     */
    @RequestMapping("/importExam")
    @ResponseBody
    public String importExam(@RequestParam MultipartFile[] file, HttpSession session) {
        int result = 0;

        try {
           result= eaxmService.insertExam(file[0]);
        } catch (Exception e) {

            e.printStackTrace();
        }

        if(result > 0){
            return "{\"result\":\"excel文件數據導入成功!\"}";
        }else{
            return "{\"result\":\"excel文件數據導入失敗!\"}";
        }
    }

7.希望對各位有幫助,後面會更新圖片上傳+編輯的操作

各位大哥覺得好的給個贊
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章