• Spring MVC 批量导入Excel文件


    Controller

    /**
    * 批量导入
    * @param file
    * @param request
    * @return
    */
    @RequestMapping(value="import-uarea",method=RequestMethod.POST)
    @ResponseBody
    public CommonModel importUArea(MultipartFile file,HttpServletRequest request){
      //判断文件是否为空
      if(file==null){
        commonModel.setCode(400);
        commonModel.setMessage("请选择文件!");
        return commonModel;
      }
      //获取文件名
      String name=file.getOriginalFilename();
      ReadExcel<UArea> readExcel=new ReadExcel<UArea>();
      if(!readExcel.validateExcel(name)){
        commonModel.setCode(400);
        commonModel.setMessage("请选择Excel文件!");
        return commonModel;
      }
      //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
      long size=file.getSize();
      if(name==null || ("").equals(name) && size==0) {
        commonModel.setCode(400);
        commonModel.setMessage("请选择文件!");
        return commonModel;
      }
      //批量导入。参数:文件名,文件。
      String result = uAreaService.batchImport(name,file);
      commonModel.setCode(200);
      commonModel.setMessage(result);
      return commonModel;
      }

    Service

    /**
    * 批量导入
    * @param name
    * @param file
    * @return
    */
    public String batchImport(String name,MultipartFile file){
      int count = 0;
      //创建处理EXCEL
      ReadExcel<UArea> readExcel=new ReadExcel<UArea>();
      //解析excel,获取区域信息集合。
      List<UArea> uAreaList = readExcel.getExcelInfo(name ,file,"uArea");
      //迭代添加区域信息
      for(UArea uArea:uAreaList){
        boolean bName = validateUArea(uArea.getAreaName(),"areaName");
        boolean bCode = validateUArea(uArea.getAreaCode(),"areaCode");
        if(bName&&bCode){
          uAreaDao.addUArea(uArea);
        count++;
        }
      }
      return "共 : " + uAreaList.size() + "条记录,成功导入 : " + count+ " 条,失败 : " + (uAreaList.size()-count) + " 条";
      }
    }

    ReadExcel.java

    package com.sinosoft.autopart.platform.common.util;

    import java.io.IOException;
    import java.io.InputStream;
    import java.text.DecimalFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;

    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.web.multipart.MultipartFile;

    import com.sinosoft.autopart.platform.domain.base.UArea;
    import com.sinosoft.autopart.platform.domain.base.ULocalOrg;
    /**
    * 获取Excel信息类
    * @author
    */
    public class ReadExcel<T> {
    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;
    //错误信息接收器
    private String errorMsg;
    //构造方法
    public ReadExcel(){}
    //获取总行数
    public int getTotalRows() { return totalRows;}
    //获取总列数
    public int getTotalCells() { return totalCells;}
    //获取错误信息
    public String getErrorInfo() { return errorMsg; }

    /**
    * 验证EXCEL文件
    * @param filePath
    * @return
    */
    public boolean validateExcel(String filePath){
      if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){
        errorMsg = "文件名不是excel格式";
        return false;
      }
      return true;
     }

    /**
    * 读EXCEL文件,获取区域信息集合
    * @param fielName
    * @return
    */
    public List<T> getExcelInfo(String fileName,MultipartFile Mfile,String flag){

      /*//把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
      CommonsMultipartFile cf= (CommonsMultipartFile)Mfile; //获取本地存储路径
      File file = new File("D:\fileupload");
      //创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
      if (!file.exists()) file.mkdirs();
      //新建一个文件
      File file1 = new File("D:\fileupload" + new Date().getTime() + ".xls");
      //将上传的文件写入新建的文件中
      try {
        cf.getFileItem().write(file1);
      } catch (Exception e) {
        e.printStackTrace();
      }*/

      //初始化区域信息的集合
      List<T> excelList=new ArrayList<T>();
      //初始化输入流
      InputStream is = null;
      try{
        //验证文件名是否合格
        if(!validateExcel(fileName)){
          return null;
        }
        //根据文件名判断文件是2003版本还是2007版本
        boolean isExcel2003 = true;
        if(WDWUtil.isExcel2007(fileName)){
          isExcel2003 = false;
        }
        //根据新建的文件实例化输入流
        is = Mfile.getInputStream();
        //根据excel里面的内容读取区域信息
        excelList = getExcelInfo(is, isExcel2003,flag);
        is.close();
      }catch(Exception e){
        e.printStackTrace();
      } finally{
        if(is !=null)
        {
        try{
          is.close();
        }catch(IOException e){
          is = null;
          e.printStackTrace();
        }
      }
    }
    return excelList;
    }
    /**
    * 根据excel里面的内容读取客户信息
    * @param is 输入流
    * @param isExcel2003 excel是2003还是2007版本
    * @return
    * @throws IOException
    */
    public List<T> getExcelInfo(InputStream is,boolean isExcel2003,String flag){
      List<T> excelList=null;
      try{
        /** 根据版本选择创建Workbook的方式 */
        Workbook wb = null;
        //当excel是2003时
        if(isExcel2003){
          wb = new HSSFWorkbook(is);
        }
        else{//当excel是2007时
        wb = new XSSFWorkbook(is);
        }
        //读取Excel里面区域的信息
        excelList=readExcelValue(wb,flag);
      }
      catch (IOException e) {
        e.printStackTrace();
      }
      return excelList;
    }
    /**
    * 读取Excel里面区域的信息
    * UArea
    * @param wb
    * @return
    */
    @SuppressWarnings("unchecked")
    private List<T> readExcelValue(Workbook wb,String flag){
      //得到第一个shell
      Sheet sheet=wb.getSheetAt(0);

      //得到Excel的行数
      this.totalRows=sheet.getPhysicalNumberOfRows();

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

      List<T> excelList=new ArrayList<T>();
      //机构(ULocalOrg)Excel导入
      Date inputDate = null;
      Date updateDate = null;
      if("uLocalOrg".equals(flag)){
        ULocalOrg uLocalOrg;
      //循环Excel行数,从第二行开始。标题不入库
        for(int r=1;r<totalRows;r++){
          Row row = sheet.getRow(r);
          if (row == null) continue;
            uLocalOrg = new ULocalOrg();
            //循环Excel的列
            for(int c = 0; c <this.totalCells; c++){
              Cell cell = row.getCell(c);
              if (null != cell){
                if(c==0){
                  uLocalOrg.setOrgName(cell.getStringCellValue());//机构名称
                }else if(c==1){
                  uLocalOrg.setOrgCode(new DecimalFormat("########").format(cell.getNumericCellValue()));//机构编码
                }else if(c==2){
                  uLocalOrg.setAreaId(cell.getStringCellValue());//区域ID
                }else if(c==3){
                  uLocalOrg.setDescription(cell.getStringCellValue());//描述说明
                }else if(c==4){
                  uLocalOrg.setDeleteFlag(new DecimalFormat().format(cell.getNumericCellValue()));//删除标志
                }else if(c==5){
                  inputDate = cell.getDateCellValue()==null?new Date():cell.getDateCellValue();
                  uLocalOrg.setInputDate(inputDate);//记录日期
                }else if(c==6){
                  uLocalOrg.setInputId(cell.getStringCellValue());//记录人
                }else if(c==7){
                  updateDate = cell.getDateCellValue();
                  if(updateDate!=null){
                    if(updateDate.getTime()<inputDate.getTime()){
                      updateDate = new Date();
                    }
                  }
                  uLocalOrg.setUpdateDate(updateDate);//修改日期
                }else if(c==8){
                  uLocalOrg.setUpdateId(cell.getStringCellValue());//修改人
                }else if(c==9){
                  uLocalOrg.setRemark(cell.getStringCellValue());//备注信息
                }
              }
            }
            // 调用java.util.UUID生成id
            String uuid = UUIDGenerator.getUUID();
            uLocalOrg.setId(uuid);
            //添加机构
            excelList.add((T)uLocalOrg);
          }
        }else{
        //区域(UArea)Excel导入
        UArea uArea;
        //循环Excel行数,从第二行开始。标题不入库
        for(int r=1;r<totalRows;r++){
          Row row = sheet.getRow(r);
            if (row == null) continue;
              uArea = new UArea();
              //循环Excel的列
              for(int c = 0; c <this.totalCells; c++){
                Cell cell = row.getCell(c);
                if (null != cell){
                  if(c==0){
                    uArea.setAreaName(cell.getStringCellValue());//区域名称
                  }else if(c==1){
                    uArea.setAreaCode(cell.getStringCellValue());//区域编码
                  }else if(c==2){
                    uArea.setDescription(cell.getStringCellValue());//描述说明
                  }else if(c==3){
                    uArea.setDeleteFlag(new DecimalFormat().format(cell.getNumericCellValue()));//删除标志
                  }else if(c==4){
                    inputDate = cell.getDateCellValue()==null?new Date():cell.getDateCellValue();
                    uArea.setInputDate(inputDate);//记录日期
                  }else if(c==5){
                      uArea.setInputId(cell.getStringCellValue());//记录人
                  }else if(c==6){
                    updateDate = cell.getDateCellValue();
                    if(updateDate!=null){
                      if(updateDate.getTime()<inputDate.getTime()){
                        updateDate = new Date();
                      }
                    }
                    uArea.setUpdateDate(updateDate);//修改日期
                  }else if(c==7){
                    uArea.setUpdateId(cell.getStringCellValue());//修改人
                  }else if(c==8){
                    uArea.setRemark(cell.getStringCellValue());//备注信息
                  }
                }
              }
              // 调用java.util.UUID生成id
              String uuid = UUIDGenerator.getUUID();
              uArea.setId(uuid);
              //添加区域
              excelList.add((T)uArea);
            }
          }
        return excelList;
      }

    }

  • 相关阅读:
    java实现趣味拼算式
    windows下安装docker
    Docker_入门?只要这篇就够了!(纯干货适合0基础小白)
    网关支付、银联代扣通道、快捷支付、银行卡支付分别是怎么样进行支付的?
    【深度解析】第三方支付的分类、接口与支付流程
    去外包公司的伙伴们小心了!——亲身经历,数数外包公司的坑
    一个tomcat下部署多个项目或一个服务器部署多个tomcat
    tomcat部署web应用的4种方法以及部署多个应用
    datatables增删改查的实现
    基于SpringMVC+Bootstrap+DataTables实现表格服务端分页、模糊查询
  • 原文地址:https://www.cnblogs.com/gaofz/p/7692167.html
Copyright © 2020-2023  润新知