spring mvc实现excel的模板下载与上传

1、模板下载

(1)模板的存储位置:WEB-INF/file/fund.xlsx

(2)下载方法: 

/**
     *  下载方法
     * @param path
     * @param id
     * @param req
     * @return
     */
    public static ResponseEntity<byte[]> download(String path, HttpServletRequest req) {
        logger.info("【文件下载】 download --> 执行开始,请求文件相对路径:" + path);
        File file = null;
        try {
//            Resource resource = new ClassPathResource(path);
//            file = resource.getFile();
//            file=new File("c:/1.xlsx");
            Resource resource=new ServletContextResource(req.getServletContext(),path);
            file = resource.getFile();
        } catch (Exception e) {
            logger.info("【文件下载】 download -->执行异常,无法加载到服务端文件,请求文件相对路径:" + path, e);
            return null;
        }
        String fileName = null;
        try {
            fileName = new String(file.getName().getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            logger.info("【文件下载】 download -->执行异常,无法解析服务端文件,请求文件相对路径:" + path, e);
            return null;
        }
        HttpHeaders header = new HttpHeaders();
        header.setContentDispositionFormData("attachment", fileName);
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        byte[] res = null;
        try {
            res = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            logger.info("【文件下载】 download -->执行异常,解析服务端文件为字节数组异常,请求文件相对路径:" + path, e);
            return null;
        }
        return new ResponseEntity<byte[]>(res, header, HttpStatus.CREATED);
    }        

(3)controller方法:

// 促销方案批量导入——模板下载
    @ResponseBody
    @RequestMapping(value ="/promotion/excel_down", method = {RequestMethod.GET}, produces = "text/plain;charset=UTF-8")
    public ResponseEntity<byte[]> downloadModel( HttpServletRequest req, ModelMap model) throws InterruptedException {
        ResponseEntity<byte[]> download = null;
        String path = "WEB-INF/file/fund.xlsx";
        try {
            download = ExcelUtils.download(path, req);
        } catch (Exception e) {
            logger.error("", e);
            e.printStackTrace();
        }
        return download;
    }
 2、excel上传

(1)前端jsp:

——css:

<style type="text/css">
    .file {
        position: relative;
          background: #D0EEFF;
        border: 1px solid #99D3F5;
        border-radius: 4px;
        padding: 6px 12px;
        margin-right: 10px;
        overflow: hidden;
        color: #1E88C7;
        text-decoration: none;
        text-indent: 0;
        line-height: 25px;
    }
    .file input {
        position: absolute;
        right: 0;
        top: 0;
        opacity: 0;
    }
    .file:hover {
        background: #AADFFD;
        border-color: #78C3F3;
        color: #004974;
        text-decoration: none;
    }
    #upfile {
        width:100px;
        height:25px;
    }
</style>

——form块:

<form method="POST"  enctype="multipart/form-data" id="form1" action="${pageContext.request.contextPath}/admin/promotion/excel_import">
      <a class='btn btn-success btn-sm mr10' href="javascript:toDown()">模板下载</a>  
       <a href="javascript:;" class="file"><i class="fa fa-upload" aria-hidden="true"></i> 选择文件  
            <input type="file" id="upfile" name="upfile" value="" /> </a>
             <button type="submit" class="btn btn-info" οnclick="return checkData()">提交</button>
</form>  

——js:

// 模板下载
        function toDown(){
             window.location.href="${pageContext.request.contextPath}/admin/promotion/excel_down";
        } 
        
        //JS校验form表单信息  
        function checkData(){  
           var fileDir = $("#upfile").val();  
           var suffix = fileDir.substr(fileDir.lastIndexOf("."));  
           if("" == fileDir){  
               alert("选择需要导入的Excel文件!");  
               return false;  
           }  
           if(".xls" != suffix && ".xlsx" != suffix ){  
               alert("选择Excel格式的文件导入!");  
               return false;  
           }  
           return true;  
        }  

(2)controller方法:

/** 促销方案批量导入——批量导入
         * 描述:通过传统方式form表单提交方式导入excel文件
         * @param request
         * @throws Exception
         */
        @RequestMapping(value="/promotion/excel_import",method = {RequestMethod.GET, RequestMethod.POST })
        public String  uploadExcel(HttpServletRequest request,ModelMap model) throws Exception {  
             MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
             System.out.println("通过传统方式form表单提交方式导入excel文件!");  
             try{
                 InputStream in =null;  
                 List<List<Object>> listob = null;  
                 MultipartFile file = multipartRequest.getFile("upfile");  
                 if(file.isEmpty()){  
                     throw new BusinessException("000024","文件不存在!");  
                 }  
                 in = file.getInputStream();  
                 listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
                 in.close();  
                //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
                List<Map<String,Object>> list = new ArrayList<>();
                for (int i = 0; i < listob.size(); i++) {
                    List<Object> lo = listob.get(i);
                    Map<String,Object> map = new HashMap<>();
                    map.put("promotionCode", String.valueOf(lo.get(0)));
                    map.put("promotionName", String.valueOf(lo.get(1)));
                    map.put("investType", String.valueOf(lo.get(2)));
                    map.put("preferType", String.valueOf(lo.get(3)));
                    map.put("startDate", String.valueOf(lo.get(4)));
                    map.put("endDate", String.valueOf(lo.get(5)));
                    map.put("tradeMethod", String.valueOf(lo.get(6)));
                    map.put("fundCompCode", String.valueOf(lo.get(7)));
                    map.put("fundCode", String.valueOf(lo.get(8)));
                    map.put("rateValue", String.valueOf(lo.get(9)));
                    map.put("checkUser",getSessionUser());
                    map.put("modifyUser",getSessionUser());
                    list.add(map);
                }
                Map<String,Object> map = new HashMap<>();
                map.put("list", list);
                Client.send(Values.url_promotion_excelImport, map);
            } catch (BusinessException e) {
                Map<String,Object> param = new HashMap<>();
                String result = Client.send(Values.url_promotion_PageList, param);
                 Map<String, Object> resultMap = JacksonUtils.json2map(result);
                 Map<String, Object> dataMap = ActionUtils.castMap(
                         resultMap.get("data"), Object.class);
                 model.addAttribute("list", dataMap.get("list"));
                 model.addAttribute("pageSize", SystemContext.getPagesize());
                 model.addAttribute("total", dataMap.get("total"));
                 model.addAllAttributes(param);
                 logger.error("", e);
                 //操作异常时需要将页面数据放入model中
                 this.putMsg(model, e);
                 return "/fundbase/promotion/list";
             } catch (Exception e){
                 logger.error("", e);
             }
            return "redirect:/admin/success?backUrl="
            + ActionUtils.toLink("/admin/promotion/browse");
        }

以上就是spring mvc的excel模板下载和上传的方法了,后面的涉及到数据分析层的逻辑,就不在这里展示了,希望能帮助到大家,谢谢!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值