使用Excel导入表格内容 - 进行批量操作

Excel格式为例,可以用来处理做批量添加/删除/发货 等功能

在这里插入图片描述

总体逻辑就是:接收到Excel表格后,从本地创建一个文件,然后循环将Excel每个单元格的内容写入到本地文件内,之后读取本地文件每个单元格的信息,存储到List实体里面。 最后循环实体取出数值,处理自己要批量做的业务就可以了。

先创建实体,放入对应的字段内容
在这里插入图片描述

//接口处理

public Map<String,Object> importShellExcel(@RequestParam(required=false, value="files") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
		LOGGER.info("Come in ShellUserController importShellExcel method");
		//获取开始时间
		long startTime = System.currentTimeMillis();
		//判断文件是否为空
		if(null == file){
			return ApiConstant.put(ApiConstant.err201, "上传失败");
		}
		//获取文件名
		String filename = file.getOriginalFilename();
		//进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
		if(filename == null || ("").equals(filename) && file.getSize() == 0){
			return ApiConstant.put(ApiConstant.err201, "上传失败");
		}

		//创建处理EXCEL
		ReadShellExcel readExcel = new ReadShellExcel();
		//解析excel,获取信息集合。
		List<AdminUserShellDto> dtoList = readExcel.getExcelInfo(filename ,file);
		if(dtoList == null || dtoList.size() == 0){
			return ApiConstant.put(ApiConstant.err201);
		}
		String adminName = getAdmin().getUsername();
		Map<String , Object> map = null ;
		try{
			//拿到数据,开始处理业务
			map = userCapitalService.importShellExcel(dtoList, adminName);
		}catch (Exception e ){
			LOGGER.error("导入贝壳表格异常 ======= " + MyPubUtil.getError(e));
			return ApiConstant.put(ApiConstant.err500);
		}
		//获取结束时间
		long endTime = System.currentTimeMillis();
		LOGGER.info("Leave ShellUserController importShellExcel method 运行时间:" + (endTime - startTime) + "ms");
		return map;
	}
//ReadShellExcel 开始处理文件

public class ReadShellExcel {
    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;
    //错误信息接收器
    private String errorMsg;
    //构造方法
    public ReadShellExcel(){}
    //获取总行数
    public int getTotalRows()  { return totalRows;}
    //获取总列数
    public int getTotalCells() {  return totalCells;}
    //获取错误信息
    public String getErrorInfo() { return errorMsg; }
    //文件路径
    private static final String FILE_PATH = PropertiesUtil.getString(BaseConstant.PROPERTIES_CONFIG, "excelImport.file.path");

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

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

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

        //初始化客户信息的集合
        List<AdminUserShellDto> dtoList = new ArrayList<>();
        //初始化输入流
        InputStream is = null;
        try{
            //验证文件名是否合格
            if(!validateExcel(fileName)){
                return null;
            }
            //根据文件名判断文件是2003版本还是2007版本
            boolean isExcel2003 = true;
            if(isExcel2007(fileName)){
                isExcel2003 = false;
            }
            //根据新建的文件实例化输入流
            is = new FileInputStream(file1);
            //根据excel里面的内容读取客户信息
            dtoList = getExcelInfo(is, isExcel2003);
            is.close();
        }catch(Exception e){
            e.printStackTrace();
        } finally{
            if(is !=null)
            {
                try{
                    is.close();
                }catch(IOException e){
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return dtoList;
    }


    /**
     * 根据excel里面的内容读取客户信息
     * @param is 输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public  List<AdminUserShellDto> getExcelInfo(InputStream is, boolean isExcel2003){
        List<AdminUserShellDto> dtoList = null;
        try{
            /** 根据版本选择创建Workbook的方式 */
            Workbook wb = null;
            //当excel是2003时
            if(isExcel2003){
                wb = new HSSFWorkbook(is);
            }
            else{//当excel是2007时
                wb = new XSSFWorkbook(is);
            }
            //读取Excel里面客户的信息
            dtoList = readExcelValue(wb);
        }
        catch (IOException e)  {
            e.printStackTrace();
        }
        return dtoList;
    }


    /**
     * 读取Excel里面客户的信息
     * @param wb
     * @return
     */
    private List<AdminUserShellDto> readExcelValue(Workbook wb){
        //得到第一个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<AdminUserShellDto> dtoList = new ArrayList<>();
        AdminUserShellDto dto;
        //循环Excel行数,从第二行开始。标题不入库
        for(int r = 1; r < totalRows; r++){
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            dto = new AdminUserShellDto();

            //循环Excel的列
            for(int c = 0; c < this.totalCells; c++){
                Cell cell = row.getCell(c);
                if (null != cell){
                    if(c==0){
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        //手机号
                        dto.setPhone(cell.getStringCellValue());
                    }else if(c==1){
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        //贝壳变动数量
                        dto.setChangeAmount(new BigDecimal(cell.getStringCellValue()));
                    }else if(c==2){
                        //收货人姓名
                        dto.setTitle(cell.getStringCellValue());
                    }
                }
            }
            //添加客户
            dtoList.add(dto);
        }
        return dtoList;
    }




    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值