POI实现Excel导入数据

1.Controller

/**
     * 导入Excel
     * @param cd
     * @param req
     * @param resp
     */
    @PostMapping("/putCarRecords")
    @RequiresPermissions("carRecord:putCarRecords")
    @ResponseBody
    Result<String> putCarRecords(MultipartFile upfile){
        String fileName=upfile.getOriginalFilename();
        long size=upfile.getSize();
        if(StringUtils.isEmpty(fileName)||size==0){
            return Result.build(Result.CODE_FAIL, "上传失败");
        }
        return carRecordService.putCarRecords(fileName, upfile);
    }

2.service

@Override
    public Result<String> putCarRecords(String name, MultipartFile file) {
        Map<String,Long> reasonMap=new HashMap<String,Long>();
        Map<String,Long> carModelMap=new HashMap<String,Long>();
        List<ReasonDO> reasonList = reasonService.selectList(null);
        List<CarModelDO> carList = carModelService.selectList(null);
        
        for(ReasonDO reason:reasonList){
            reasonMap.put(reason.getReasonName(), reason.getReasonId());
        }
        for(CarModelDO carModelDO:carList){
            carModelMap.put(carModelDO.getCarModelName(), carModelDO.getCarModelId());
        }
        //解析excel,获取客户信息集合。
        try {
            List<CarRecordDO> carRecordDOs = ExcelUtil.getExcelInfo(name, file, reasonMap, carModelMap);
            if(carRecordDOs != null){
                if(carRecordDOs.size()!=0){
                    insertBatch(carRecordDOs);
                    return Result.ok();
                }
                return Result.build(Result.CODE_FAIL, "请至少上传一条数据!!");
                
            }else{
                return Result.build(Result.CODE_FAIL, "插入失败!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.build(Result.CODE_FAIL, e.getMessage());
        }

       
    }

3.ExcelUtil

 /**
     * 读EXCEL文件,获取客户信息集合
     * @param
     * @return
     */
    public static List<CarRecordDO> getExcelInfo(String fileName, MultipartFile Mfile,Map<String,Long> resonMap,Map<String,Long> carModelMap){

        //初始化客户信息的集合
        List<CarRecordDO> customerList=new ArrayList<CarRecordDO>();
        //初始化输入流
        InputStream is = null;
        try{
            //验证文件名是否合格
            if(!validateExcel(fileName)){
                return null;
            }
            //根据文件名判断文件是2003版本还是2007版本
            boolean isExcel2003 = true;
            if(WDWUtil.isExcel2007(fileName)){
                isExcel2003 = false;
            }
            //根据新建的文件实例化输入流
            is =  Mfile.getInputStream();
            //根据excel里面的内容读取客户信息
            customerList = getExcelInfo(is, isExcel2003, resonMap, carModelMap);
            is.close();
        }catch(Exception e){
            throw new RuntimeException(e.getMessage());
        } finally{
            if(is !=null)
            {
                try{
                    is.close();
                }catch(IOException e){
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return customerList;
    }
    /**
     * 根据excel里面的内容读取客户信息
     * @param is 输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    private static  List<CarRecordDO> getExcelInfo(InputStream is,boolean isExcel2003,Map<String,Long> resonMap,Map<String,Long> carModelMap){
        List<CarRecordDO> customerList=null;
        try{
            /** 根据版本选择创建Workbook的方式 */
            Workbook wb = null;
            //当excel是2003时
            if(isExcel2003){
                wb = new HSSFWorkbook(is);
            }
            else{//当excel是2007时
                wb = new XSSFWorkbook(is);
            }
            //读取Excel里面客户的信息
            customerList=readExcelValue(wb, resonMap,carModelMap);
        }
        catch (IOException e)  {

            throw new RuntimeException(e.getMessage());
        }
        return customerList;
    }
    /**
     * 读取Excel里面客户的信息
     * @param wb
     * @return
     */
    private static List<CarRecordDO> readExcelValue(Workbook wb,Map<String,Long> resonMap,Map<String,Long> carModelMap){
        //得到第一个shell
        Sheet sheet=wb.getSheetAt(0);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");

        //得到Excel的行数  物理行数
        //int totalRows=sheet.getPhysicalNumberOfRows();
        int totalRows=sheet.getLastRowNum()+1;
        //得到列数
        int totalCells=0;

        //得到Excel的列数(前提是有行数)
        if(totalRows>=1 && sheet.getRow(0) != null){
            totalCells=sheet.getRow(6).getPhysicalNumberOfCells();
        }

        List<CarRecordDO> cardRecords=new ArrayList<CarRecordDO>();
        CarRecordDO cardRecordDO;
        //循环Excel行数,从第8行开始。标题不入库
        for(int r=7;r<totalRows;r++){
            Row row = sheet.getRow(r);
            if (row == null) continue;
            cardRecordDO=new CarRecordDO();
            //循环Excel的列
            for(int c = 0; c <=totalCells; c++){
                    Cell cell = row.getCell(c);
                    switch(c){
                    case 0:
                        if(cell==null){
                            throw new RuntimeException("请填写车主姓名");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String carOwnerName=cell.getStringCellValue();
                        cardRecordDO.setCarOwnerName(carOwnerName.replace(" ", ""));
                        break;
                    case 1:
                        if(cell==null){
                            throw new RuntimeException("请填写车主电话");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue = cell.getStringCellValue();
                        cardRecordDO.setCarOwnerTel(stringCellValue.replace(" ", ""));
                        break;
                    case 2:
                        String stringCellValue2 = cell.getStringCellValue();
                        if(!StringUtils.isEmpty(stringCellValue2)){
                            cardRecordDO.setCarNumber(stringCellValue2.replace(" ", ""));
                        }
                        break;
                    case 3:
                        if(cell==null){
                            throw new RuntimeException("请填写车型");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue3 = cell.getStringCellValue();
                        if(carModelMap.containsKey(stringCellValue3)){
                            cardRecordDO.setCarModelId(carModelMap.get(stringCellValue3.replace(" ", "")));
                        }else{
                            throw new RuntimeException("请选择指定车型");
                        }
                        
                        break;
                    case 4:
                        if(cell==null){
                            continue;
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue4 = cell.getStringCellValue();
                        if(!StringUtils.isEmpty(stringCellValue4)){
                            if(resonMap.containsKey(stringCellValue4)){
                                cardRecordDO.setReasonId(resonMap.get(stringCellValue4.replace(" ", "")));
                            }else{
                                throw new RuntimeException("请填写正确进场原因");
                            }
                        }
                        break;
                    case 5:
                        if(cell==null){
                            throw new RuntimeException("请输入进场值班员");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue5 = cell.getStringCellValue();
                        cardRecordDO.setInUserName(stringCellValue5.replace(" ", ""));
                        break;
                    case 6:
                        if(cell==null){
                            throw new RuntimeException("请输入进场时间");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue6 = cell.getStringCellValue();
                        try {
                            cardRecordDO.setInTime(sdf.parse(stringCellValue6.replace(" ", "")));
                        } catch (ParseException e) {
                            
                            throw new RuntimeException("时间格式错误");
                        }
                        break;
                    case 7:
                        if(cell==null){
                            continue;
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue7 = cell.getStringCellValue();
                        if(!StringUtils.isEmpty(stringCellValue7)){
                            try {
                                cardRecordDO.setOutTime(sdf.parse(stringCellValue7.replace(" ", "")));
                            } catch (ParseException e) {
                                throw new RuntimeException("时间格式错误");
                            }
                        }
                        break;
                    case 8:
                        if(cell==null){
                            continue;
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue8 = cell.getStringCellValue();
                        if(!StringUtils.isEmpty(stringCellValue8)){
                            cardRecordDO.setOutUserName(stringCellValue8.replace(" ", ""));
                        }
                        break;
                    case 9:
                        if(cell==null){
                            throw new RuntimeException("请输入受理单位");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String stringCellValue9 = cell.getStringCellValue();
                        cardRecordDO.setAcceptanceUnit(stringCellValue9);
                        break;
                    case 10:
                        if(cell==null){
                            throw new RuntimeException("请输入发送机型号");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String engineNumber = cell.getStringCellValue();
                        cardRecordDO.setEngineNumber(engineNumber);
                        break;
                    case 11:
                        if(cell==null){
                            throw new RuntimeException("请输入车架号");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String vinNo = cell.getStringCellValue();
                        cardRecordDO.setVinNo(vinNo);
                        break;
                    case 12:
                        if(cell==null){
                            throw new RuntimeException("请输入事发地点");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String accidentAddress = cell.getStringCellValue();
                        cardRecordDO.setAccidentAddress(accidentAddress);
                        break;
                    case 13:
                        if(cell==null){
                            throw new RuntimeException("请输入停放区域");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String parkedArea = cell.getStringCellValue();
                        cardRecordDO.setParkedArea(parkedArea);
                        break;
                    case 14:
                        if(cell==null){
                            throw new RuntimeException("请输入经办人");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String agent = cell.getStringCellValue();
                        cardRecordDO.setAgent(agent);
                        break;
                    
                    
                    case 15:
                        if(cell==null){
                            throw new RuntimeException("请选择状态");
                        }
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String statusStr = cell.getStringCellValue();
                        if(statusStr.replace(" ", "").equals("进场")){
                            cardRecordDO.setStatus(0);
                        }else if(statusStr.replace(" ", "").equals("出场")){
                            cardRecordDO.setStatus(1);
                        }else{
                            throw new RuntimeException("请选择正确状态");
                        }
                        break;
                    }
                //添加客户
            }
            cardRecords.add(cardRecordDO);
        }
        return cardRecords;
    }

4.前端

$(".filebox").on("change","#file",function(){
    //得到文件路径
    var filePath = $('#file').val();
    if(filePath!=""){
        //对文件格式进行验证(简单验证)
        var d1=/\.[^\.]+$/.exec(filePath);
        if(d1==".xls"){
              var formData=new FormData();
              formData.append("upfile",$("#file")[0].files[0]);
              $.ajax({
                url:prefix+'/putCarRecords',
                type:'POST',
                data:formData,
                /*
                改成contentType为false才会加上正确的ContentType
                */
                contentType: false,
                  /**
                  * 必须false才会避开jQuery对 formdata 的默认处理
                  * XMLHttpRequest会对 formdata 进行正确的处理
                  */
                  processData: false,
                  success: function (data) {
                      if(data.code==0){
                          window.location.reload();
                      }else{
                          layer.msg(data.msg);
                          $("#file").val("");
                      }
                  },
                  error:function(){
                      layer.msg("网络错误!");
                      $("#file").val("");
                  }
            });
        }else{
            layer.msg("请选择.xls文件");
        }
    }else{
        layer.msg("请选择.xls文件!");
    }
});
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • 1.环境准备 centos7 1.1、yum安装设置 yum list |grep openstackcentos...
    davisgao阅读 5,439评论 1 16
  • 1.Pod Pod是k8s的最基本的操作单元,包含一个或多个紧密相关的容器,类似于豌豆荚的概念。一个Pod可以被一...
    jony456123阅读 7,381评论 0 5
  • 对于java中的思考的方向,1必须要看前端的页面,对于前端的页面基本的逻辑,如果能理解最好,不理解也要知道几点。 ...
    神尤鲁道夫阅读 782评论 0 0
  • 一、部署基础环境:A.IP地址规划:controller节点:192.168.0.201,compute节点:19...
    stone2020阅读 2,810评论 0 1
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,067评论 1 32