码迷,mamicode.com
首页 > 其他好文 > 详细

批量导入数据(excel模板文件方式)

时间:2020-06-02 23:11:04      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:spring   判断   date()   v-for   service   actor   col   alibaba   wired   

批量导入数据:

1.在webapp下的template文件下导入excel模板文件

1.前端:提供下载模板文件
    <!DOCTYPE html>
    <html>
        <head>
            <!-- 页面meta -->
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <title>传智健康</title>
            <meta name="description" content="传智健康">
            <meta name="keywords" content="传智健康">
            <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
            <!-- 引入样式 -->
            <link rel="stylesheet" href="../plugins/elementui/index.css">
            <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
            <link rel="stylesheet" href="../css/style.css">
            <link rel="stylesheet" href="../css/orderset.css">
            <!-- 引入组件库 -->
            <script src="../js/vue.js"></script>
            <script src="../plugins/elementui/index.js"></script>
            <script type="text/javascript" src="../js/jquery.min.js"></script>
            <script src="../js/axios-0.18.0.js"></script>
        </head>
        <body class="hold-transition">
        <div id="app">
            <div class="content-header">
                <h1>预约管理<small>预约设置</small></h1>
                <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
                    <el-breadcrumb-item :to="{ path: ‘/‘ }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>预约管理</el-breadcrumb-item>
                    <el-breadcrumb-item>预约设置</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="app-container">
                <div class="box">
                    <div class="box ordersetting">
                        <el-card class="box-card">
                            <div class="boxMain">
                                <el-button style="margin-bottom: 20px;margin-right: 20px" type="primary" @click="downloadTemplate()">模板下载</el-button>
                                <el-upload action="/ordersetting/upload.do"
                                           name="excelFile"
                                           :show-file-list="false"
                                           :on-success="handleSuccess"
                                           :before-upload="beforeUpload">
                                    <el-button type="primary">上传文件</el-button>
                                </el-upload>
                            </div>
                            <div>
                                操作说明:请点击"模板下载"按钮获取模板文件,在模板文件中录入预约设置数据后点击"上传文件"按钮上传模板文件。
                            </div>
                        </el-card>
                        <div class="calendar">
                            <!-- 年份 月份 -->
                            <div class="month">
                                <div class="currentdate">
                                    <span class="choose-year">{{ currentYear }}年</span>
                                    <span class="choose-month">{{ currentMonth }}月</span>
                                </div>
                                <div class="choose">
                                    <span @click="goCurrentMonth(currentYear,currentMonth)" class="gotoday">今天</span>
                                    <span @click="pickPre(currentYear,currentMonth)">?</span>
                                    <span @click="pickNext(currentYear,currentMonth)">?</span>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <!-- 星期 -->
                            <div class="caldate">
                                <ul class="weekdays">
                                    <li>周一</li>
                                    <li>周二</li>
                                    <li>周三</li>
                                    <li>周四</li>
                                    <li>周五</li>
                                    <li>周六</li>
                                    <li>周日</li>
                                </ul>
                                <!-- 日期 -->
                                <ul class="days">
                                    <!-- v-for循环 每一次循环用<li>标签创建一天 -->
                                    <li v-for="dayobject in days">
                                        <template>
                                            <!-- 非当前月份 -->
                                            <div class="other-month" v-if="dayobject.day.getMonth()+1 != currentMonth">
                                                {{ dayobject.day.getDate() }}
                                            </div>
                                            <!-- 当前月 -->
                                            <div class="everyday" v-if="dayobject.day.getMonth()+1 == currentMonth">
                                                <span class="datenumber">{{ dayobject.day.getDate()}}</span>
                                                
                                                <template>
                                                    <template v-for="obj in leftobj">
                                                        <template v-if="obj.date == dayobject.day.getDate()">
                                                            <template v-if="obj.number > obj.reservations">
                                                                <div class="usual">
                                                                    <p>可预约{{obj.number}}人</p>
                                                                    <p>已预约{{obj.reservations}}人</p>
                                                                </div>
                                                            </template>
                                                            <template v-else>
                                                                <div class="fulled">
                                                                    <p>可预约{{obj.number}}人</p>
                                                                    <p>已预约{{obj.reservations}}人</p>
                                                                    <p>已满</p>
                                                                </div>
                                                            </template>
                                                        </template>
                                                    </template>
                                                    <button v-if="dayobject.day > today" @click="handleOrderSet(dayobject.day)" class="orderbtn">设置</button>
                                                </template>
                                                
                                            </div>
                                        </template>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </body>
        <!-- 引入组件库 -->
        <script src="../js/vue.js"></script>
        <script src="../plugins/elementui/index.js"></script>
        <script type="text/javascript" src="../js/jquery.min.js"></script>
        <script>
            new Vue({
                el: ‘#app‘,
                data:{
                    today:new Date(),//当前日期
                    currentDay: 1,
                    currentMonth: 1,
                    LocalMonth: 1,
                    currentYear: 1970,
                    currentWeek: 1,
                    days: [],
                    leftobj: []//用于装载页面显示的月份已经进行预约设置的数据
                },
                created: function () {//在vue初始化时调用
                    // 1:初始化当前时间对应的日期,在页面上展示日历
                    this.initData(null);
                    // 2:初始化当前月对应的预约设置的数据,把预约设置信息,显示到页面上,对模型leftobj赋值
                    this.createData();
                },
                methods: {
                    createData(){
                        // 传递当前月(date=2020-2),返回Map(json形式)
                        axios.get("/ordersetting/findOrderSettingMapByMonth.do?date="+this.currentYear+"-"+this.currentMonth).then(response=>{
                            // 返回Result(flag,message,data) data:Map(map结构的key:date、number、reservations)
                            if(response.data.flag){
                                this.leftobj = response.data.data; // 组织数据结构
                                this.$message({
                                    type:"success",
                                    message:response.data.message
                                })
                            }else{
                                this.$message({
                                    type:"error",
                                    message:response.data.message
                                })
                            }
                        }).catch((error)=>{

                        })
                    },
                    //预约设置
                    handleOrderSet(day){
                    },
                    //上传之前进行文件格式校验
                    beforeUpload(file){
                        const isXLS = file.type === ‘application/vnd.ms-excel‘;
                        if(isXLS){
                            return true;
                        }
                        const isXLSX = file.type === ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet‘;
                        if (isXLSX) {
                            return true;
                        }
                        this.$message.error(‘上传文件只能是xls或者xlsx格式!‘);
                        return false;
                    },
                    //下载模板文件
                    downloadTemplate(){
                        window.location.href="../../template/ordersetting_template.xlsx";
                    },
                    //上传成功提示(ElementUI)
                    handleSuccess(response, file) {
                        // 返回Result(flag,message,data)
                        if(response.flag){
                            this.$message({
                                message: response.message,
                                type: ‘success‘
                            });
                        }else{
                            this.$message.error(response.message);
                        }
                        // console.log(response, file, fileList);
                    },
                    //初始化当前页要展示的日期
                    initData: function (cur) {
                        var date;
                        var index = 0;   //控制显示预定的天数
                        if (cur) {
                            date = new Date(cur);
                        } else {
                            var now = new Date();
                            var d = new Date(this.formatDate(now.getFullYear(), now.getMonth()+1, 1));
                            d.setDate(35);
                            date = new Date(this.formatDate(d.getFullYear(), d.getMonth(), 1));
                        }
                        this.currentDay = date.getDate();
                        this.currentYear = date.getFullYear();
                        this.currentMonth = date.getMonth() + 1;
                        this.currentWeek = date.getDay(); // //本月第一天是周几(周日0 周六 6)
                        var today = new Date();
                        this.LocalMonth = today.getMonth() + 1;
                        if (this.currentWeek == 0) {
                            this.currentWeek = 7;
                        }
                        var str = this.formatDate(this.currentYear, this.currentMonth, this.currentDay);
                        this.days.length = 0;
                        // 今天是周日,放在第一行第7个位置,前面6个
                        //初始化本周
                        for (var i = this.currentWeek - 1; i >= 0; i--) {
                            var d = new Date(str);
                            d.setDate(d.getDate() - i);
                            var dayobject = {};
                            dayobject.day = d;
                            var now = new Date();
                            if (d.getDate() === (now.getDate()) && d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear()) {
                                dayobject.index = index++;//从今天开始显示供预定的数量
                            }
                            else if (index != 0 && index < 3)
                                dayobject.index = index++;//从今天开始3天内显示供预定的数量
                            this.days.push(dayobject);//将日期放入data 中的days数组 供页面渲染使用
                        }
                        //其他周
                        for (var i = 1; i <= 35 - this.currentWeek; i++) {
                            var d = new Date(str);
                            d.setDate(d.getDate() + i);
                            var dayobject = {};//dayobject   {day:date,index:2}
                            dayobject.day = d;
                            var now = new Date();
                            if (d.getDate() === (now.getDate()) && d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear()) {
                                dayobject.index = index++;
                            }
                            else if (index != 0 && index < 3)
                                dayobject.index = index++;
                            this.days.push(dayobject);
                        }
                        
                        /**this.leftobj = [
                            { date: 1, number: 120, reservations: 1 },
                            { date: 3, number: 120, reservations: 1 },
                            { date: 4, number: 120, reservations: 120 },
                            { date: 6, number: 120, reservations: 1 },
                            { date: 8, number: 120, reservations: 1 }
                        ];*/
                    },
                    //切换到当前月份
                    goCurrentMonth: function (year, month) {
                        var d = new Date();
                        // 初始化日历
                        this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
                        // 初始化当前月的预约设置信息
                        this.createData();
                    },
                    //向前一个月
                    pickPre: function (year, month) {
                        // setDate(0); 上月最后一天
                        // setDate(-1); 上月倒数第二天
                        // setDate(dx) 参数dx为 上月最后一天的前后dx天
                        var d = new Date(this.formatDate(year, month, 1));
                        d.setDate(0);
                        this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
                        // 初始化当前月的预约设置信息
                        this.createData();
                    },
                    //向后一个月
                    pickNext: function (year, month) {
                        var d = new Date(this.formatDate(year, month, 1));
                        d.setDate(35);////获取指定天之后的日期
                        this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
                        // 初始化当前月的预约设置信息
                        this.createData();
                    },
                    // 返回 类似 2016-01-02 格式的字符串
                    formatDate: function (year, month, day) {
                        var y = year;
                        var m = month;
                        if (m < 10) m = "0" + m;
                        var d = day;
                        if (d < 10) d = "0" + d;
                        return y + "-" + m + "-" + d
                    }
                }
            })
        </script>
    </html>
    
后端:实体类封装模板文件对应的数据
    1.模板对应的实体类:
        package com.itheima.health.pojo;

        import java.io.Serializable;
        import java.util.Date;

        /**
         * 预约设置
         */
        public class OrderSetting implements Serializable{
            private Integer id ;
            private Date orderDate;//预约设置日期
            private int number;//可预约人数
            private int reservations ;//已预约人数

            public OrderSetting() {
            }

            public OrderSetting(Date orderDate, int number) {
                this.orderDate = orderDate;
                this.number = number;
            }

            public Integer getId() {
                return id;
            }

            public void setId(Integer id) {
                this.id = id;
            }

            public Date getOrderDate() {
                return orderDate;
            }

            public void setOrderDate(Date orderDate) {
                this.orderDate = orderDate;
            }

            public int getNumber() {
                return number;
            }

            public void setNumber(int number) {
                this.number = number;
            }

            public int getReservations() {
                return reservations;
            }

            public void setReservations(int reservations) {
                this.reservations = reservations;
            }
        }

2.Controller
    package com.itheima.health.controller;

    import com.alibaba.dubbo.config.annotation.Reference;
    import com.itheima.health.constant.MessageConstant;
    import com.itheima.health.entity.Result;
    import com.itheima.health.pojo.OrderSetting;
    import com.itheima.health.service.OrderSettingService;
    import com.itheima.health.utils.POIUtils;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;

    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;

    /**
     * @ClassName OrderSettingContoller
     * @Description TODO
     * @Author ly
     * @Company 深圳黑马程序员
     * @Date 2020/2/13 16:04
     * @Version V1.0
     */
    @RestController
    @RequestMapping(value = "/ordersetting")
    public class OrderSettingContoller {

        @Reference// 订阅 dubbo注解
        OrderSettingService orderSettingService;

        // 批量导入预约设置(通过Excel完成)
        @RequestMapping(value = "/upload")
        public Result upload(MultipartFile excelFile){
            try {
                // 读取Excel文件,并批量导入到数据库
                List<String[]> list = POIUtils.readExcel(excelFile);
                // 将List<String[]>集合,转换成List<OrderSetting>
                if(list!=null && list.size()>0){
                    List<OrderSetting> orderSettingList = new ArrayList<>();
                    for (String[] strings : list) {
                        OrderSetting orderSetting = new OrderSetting(new Date(strings[0]),Integer.parseInt(strings[1]));
                        orderSettingList.add(orderSetting);
                    }
                    // 批量导入
                    orderSettingService.addList(orderSettingList);
                }
                return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
            }
        }

        // 根据传递的年月(2020-2),获取当前月对应的日期数据
        @RequestMapping(value = "/findOrderSettingMapByMonth")
        public Result findOrderSettingMapByMonth(String date){
            try {
                List<Map<String,Object>> list = orderSettingService.findOrderSettingMapByMonth(date);
                return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS,list);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
            }
        }
    }

2.Service:
    package com.itheima.health.service;

    import com.itheima.health.pojo.OrderSetting;

    import java.util.List;
    import java.util.Map;

    public interface OrderSettingService {

        void addList(List<OrderSetting> orderSettingList);

        List<Map<String,Object>> findOrderSettingMapByMonth(String date);
    }

impl:

        package com.itheima.health.service.impl;

        import com.alibaba.dubbo.config.annotation.Service;
        import com.itheima.health.dao.OrderSettingDao;
        import com.itheima.health.pojo.OrderSetting;
        import com.itheima.health.service.OrderSettingService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.transaction.annotation.Transactional;

        import java.util.ArrayList;
        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;

        /**
         * @ClassName OrderSettingServiceImpl
         * @Description TODO
         * @Author ly
         * @Company 深圳黑马程序员
         * @Date 2020/2/13 16:03
         * @Version V1.0
         */
        @Service // dubbo提供
        @Transactional
        public class OrderSettingServiceImpl implements OrderSettingService {

            @Autowired
            OrderSettingDao orderSettingDao;

            @Override
            public void addList(List<OrderSetting> orderSettingList) {
                // 批量导入
                if(orderSettingList!=null && orderSettingList.size()>0){
                    for (OrderSetting orderSetting : orderSettingList) {
                        // 判断当前预约设置时间是否已经存在,如果已经存在,执行更新;如果不存在,再执行新增
                        // 1:使用预约设置时间,查询预约设置,判断是否存在
                        long count = orderSettingDao.findOrderSettingCountByOrderDate(orderSetting.getOrderDate());
                        // 2:如果已经存在,执行更新
                        if(count>0){
                            // 根据预约设置时间(orderDate字段),更新最多预约人数(number)
                            orderSettingDao.updateNumberByOrderDate(orderSetting);
                        }
                        // 3:如果不存在,再执行新增
                        else{
                            // 保存预约设置表
                            orderSettingDao.add(orderSetting);
                        }

                    }
                }
            }

            @Override
            public List<Map<String,Object>> findOrderSettingMapByMonth(String date) {
                // 根据当前年月,获取日期(也可以完成)
                // 开始时间
                String beginDate = date+"-1";
                // 结束时间
                String endDate = date+"-31";
                // 组织查询条件
                Map paramsMap = new HashMap();
                paramsMap.put("beginDate",beginDate);
                paramsMap.put("endDate",endDate);
                // 使用查询条件完成查询
                List<OrderSetting> list = orderSettingDao.findOrderSettingByMonthBetween(paramsMap);
                // 组织需要返回的数据
                List<Map<String,Object>> mapList = new ArrayList<>();
                if(list!=null && list.size()>0){
                    for (OrderSetting orderSetting : list) {
                        Map<String,Object> map = new HashMap<>();
                        map.put("date",orderSetting.getOrderDate().getDate()); // 获取当前日期(1-31)
                        map.put("number",orderSetting.getNumber());
                        map.put("reservations",orderSetting.getReservations());
                        mapList.add(map);
                    }
                }
                return mapList;
            }
        }

Dao:

    package com.itheima.health.dao;

    import com.itheima.health.pojo.OrderSetting;

    import java.util.Date;
    import java.util.List;
    import java.util.Map;

    public interface OrderSettingDao {

        void add(OrderSetting orderSetting);

        long findOrderSettingCountByOrderDate(Date orderDate);

        void updateNumberByOrderDate(OrderSetting orderSetting);

        List<OrderSetting> findOrderSettingByMonthBetween(Map paramsMap);
    }

Dao.xml:
    <?xml version="1.0" encoding="utf-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.itheima.health.dao.OrderSettingDao">

        <!--新增保存-->
        <insert id="add" parameterType="ordersetting">
            insert into t_ordersetting(orderDate,number,reservations) values (#{orderDate},#{number},#{reservations})
        </insert>

        <!--根据预约设置时间,查询预约设置的数量-->
        <select id="findOrderSettingCountByOrderDate" parameterType="date" resultType="long">
            SELECT COUNT(*) FROM t_ordersetting WHERE orderDate = #{orderDate}
        </select>

        <!--根据预约设置时间,更新最多预约人数-->
        <update id="updateNumberByOrderDate" parameterType="ordersetting">
            update t_ordersetting set number = #{number} where orderDate = #{orderDate}
        </update>

        <!--根据当前年月,查询当前年月对应的预约设置数据(范围查询)-->
        <select id="findOrderSettingByMonthBetween" parameterType="map" resultType="ordersetting">
            SELECT * FROM t_ordersetting WHERE orderDate BETWEEN #{beginDate} AND #{endDate}
        </select>
    </mapper>





层级结构数据模板:https://blog.csdn.net/zyq1084577627/article/details/78727623




 

批量导入数据(excel模板文件方式)

标签:spring   判断   date()   v-for   service   actor   col   alibaba   wired   

原文地址:https://www.cnblogs.com/lyle-liu/p/13034303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!