POI完成Excel的导入导出数据库的功能

环境:

JDK 1.8,springboot 2.0 ,mybaties plus, layui

本文两个点,一个是导出模板给用户,一个是用户上传的文件导入到数据库中,使用的是POI

我们先引入poi的依赖

<!-- excel导入 -->
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.9</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.9</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml-schemas</artifactId>
   <version>3.9</version>
</dependency>
<!-- excel结束 -->

一, 导出模板

前端代码, 我这里使用的是阿里云

1.下载模板的按钮HTML代码

<button type="button" class="layui-btn" @click="download">
   下载模板
</button>

 2.js代码

download: function(){
    window.open(baseURL + "oagoal/downloadExcel");
},

3.controller

@RequestMapping(value = "/downloadExcel",method = RequestMethod.GET)
	public void download(HttpServletResponse res)  {
		//定义文件名
		String fileName = "oagoal.xls";
        //设置响应头
		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[1024];
        //高效输入流
		BufferedInputStream bis = null;
        //输出流
		OutputStream os = null;
        try {
            //获得输出流
            os = res.getOutputStream();
            File path = null;
            //文件位置
            path = new File(ResourceUtils.getURL("classpath:").getPath());
			bis = new BufferedInputStream(new FileInputStream(new File(path.getAbsolutePath(),"statics/doc/" + fileName)));
			int i = bis.read(buff);
               
			while(i != -1){
				os.write(buff,0,buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
            e.printStackTrace();
        }  finally {
			try {
				if(bis != null){
					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

模板是放在项目里的目录里的,这个是简单的输出流,下载模板

一, 上传Excel文件导入到数据库

1.按钮的html代码

<button type="button" class="layui-btn" id="test1">
			<i class="layui-icon">&#xe67c;</i>批量上传
		</button>

2.上传的js代码

layui.use('upload', function() {
        var upload = layui.upload;
    //执行实例
    var uploadInst2 = upload.render({
        elem: '#test1' //绑定元素
        ,url: baseURL + 'oagoal/uploadExcel'  //上传接口
        ,accept: 'file'
        ,before: function(obj){ 
            layer.load(); //上传loading
        }
        ,done: function(res){
            //上传完毕回调
            if (res.code == 0) {
                layer.msg('操作成功', {
                    icon: 1,
                    time: 1000
                }, function() {
                    layer.closeAll('loading'); //关闭loading
                    vm.reload();
                    closeRight();
                });
            } else {
                layer.msg(res.msg, {
                    time: 1000
                });
            }
        }
        ,error: function(){
            //请求异常回调
            layer.closeAll('loading'); //关闭loading
            // 请求异常回调
            layer.msg('上传失败', {
                time: 1000
            });
        }
    });
    });

3.controller层

@RequestMapping("/uploadExcel")
	public R upload(@RequestParam MultipartFile file) throws Exception {
		if(file.isEmpty()){
			throw new RRException("上传文件不能为空");
		}

		//文件后缀
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		//文件名和大小
		String name = file.getOriginalFilename();
		Long size = file.getSize();
		if(name == null || ("").equals(name) && size == 0 ){
			throw new ApplicationException("上传文件不能为空");
		}
		boolean b = oaGoalService.batchImport(name, file);
		R r ;
		if(b){
			r = R.ok();
		}else{
			r = R.error("批量导入错误");
		}
		return r;
	}

3.service代码

/*
     * @Author YL
     * @Description //TODO controller调用的入口
     * @Date 23:05 2018/8/16
     * @Param name 文件名
     * @return
     **/

 @Override
    @Transactional
    public boolean batchImport(String name, MultipartFile file) {
        List<OaGoalEntity> goalList = this.getListByEcxel(name, file);
        if(goalList.size() > 0 && goalList != null){
            this.insertBatch(goalList);
            return true;
        }
        return false;
    }


    public List<OaGoalEntity> getListByEcxel(String name,MultipartFile file){
        List<OaGoalEntity> goalList = new ArrayList<>();
        //输入流
        InputStream buffIn = null;
        if(validName(name)){
            //默认认为是2003
            boolean isExcel2003 = true;
            if(this.isExcel2007(name)){
                //是2007版本
                isExcel2003 = false;
            }
            try {
                //获得输入流
                buffIn =  file.getInputStream();
                Workbook wb = null;
                if(isExcel2003){
                    wb = new HSSFWorkbook(buffIn);
                }else{
                    wb = new XSSFWorkbook(buffIn);
                }
                goalList = this.getExcelByWorkBook(wb);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }

        }
        return  goalList;
    }


   
    /*
     * @Author YL
     * @Description //TODO 从流读取数据
     * @Date 23:05 2018/8/16
     * @Param
     * @return
     **/

    public List<OaGoalEntity> getExcelByWorkBook(Workbook wb){
        List<OaGoalEntity> goalList = null;
        //获得第一个sheet
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        Integer totalRows = sheet.getPhysicalNumberOfRows();
        //判断是否有行数
        Integer totalCells = 0;
        List<SysConfigEntity> listByOagoalType =  sysConfigService.queryKeyOrValue("cf_goal_type");

        List<SysConfigEntity> listByOagoalChargeType =  sysConfigService.queryKeyOrValue("cf_goal_charge_type");
        if(totalRows > 0 && sheet.getRow(0) != null){
            //得到列数
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        Long empId = userEntity.getEmpId();

         goalList = new ArrayList<OaGoalEntity>();
        OaGoalEntity oaGoalEntity = null;
        SysDeptEntity dept = null;
        SysDeptEntity createDept = null;
        //循环取值
        for(int r = 1;r < totalRows;r++){
            //获得当前这一行
            Row row = sheet.getRow(r);
            if(row == null){
                //如果为空跳出本次循环
                continue;
            }
            oaGoalEntity = new OaGoalEntity();
            //循环列
            for(int c = 0;c < totalCells;c++){
                Cell cell = row.getCell(c);
                if(cell != null){
                    // 将区域编号的cell中的内容当做字符串处理
                    cell.setCellType(Cell.CELL_TYPE_STRING);
/**
    这里省略了一部分代码,根据自己的实体来做
*/
                    if (c == 0) {

                    } else if (c == 1) {
                        oaGoalEntity.setDescription(cell.getStringCellValue().trim());
                    }else if(c == 15){
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = null;
                        try {
                            date = format.parse(cell.getStringCellValue().trim());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        oaGoalEntity.setStartTime(date);
                    }else if(c == 16){
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = null;
                        try {
                            date = format.parse(cell.getStringCellValue().trim());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        oaGoalEntity.setEndTime(date);
                    }
                }
            }
            goalList.add(oaGoalEntity);

        }

        return goalList;
    }


    /*
     * @Author YL
     * @Description //TODO 验证Excel文件
     * @Date 22:48 2018/8/16
     * @Param [name]
     * @return boolean
     **/
    public boolean validName(String name){
        if(name == null || !(this.isExcel2003(name) || !this.isExcel2007(name))){
           throw new ApplicationException("文件不是Excel格式");
        }
        return true;
    }
    /*
     * @Author YL
     * @Description //TODO 判断什么版本的excel
     * @Date 22:46 2018/8/16
     * @Param [name]
     * @return boolean
     **/
    public boolean isExcel2003(String name){
        return name.matches("^.+\\.(?i)(xls)$");
    }

    public boolean isExcel2007(String name){
        return name.matches("^.+\\.(?i)(sxls)$");
    }

 

猜你喜欢

转载自blog.csdn.net/qq_42276876/article/details/81775786
今日推荐