zoukankan      html  css  js  c++  java
  • poi 导入Excel --实战代码__TDBS/OMS专用(导入一行过一排排那种/工具类导入/复制代码用)

    html代码

    <a class="btn btn-primary fa fa-import" href="javascript:void(0);" id="importExcel"><span>导入excel</span></a> 
    或者

    <div class="group"><a class="link import" id="importExcel"><span></span>导入excel</a></div>

    
    

    js代码

    <script type="text/javascript">
        $(function() {
            //导入基础数据
            $("#importExcel").click(function() {
                                var url = __ctx+ '/platform/xxx/xxx/importExcel.htm';
                                importExcel(url);//导入数据
                            });
    
        });
    
        /**
         * 产生导入对话框,并打开
         * @param  actionUrl  请求的Url
         */
        function importExcel(actionUrl) {
            var f = document.createElement("form");
            var i = document.createElement("input");
            f.name = 'myFrom';
            f.action = actionUrl;
            f.method = "post";
            i.type = "file";
            i.name = "xmlFile";
            $(i).css("display", "none");
            $(i).attr("onchange", "importData('" + actionUrl + "')");
            //$(i).attr("accept", ".xls");
            $(i).attr("accept", [ '.xls', '.xlsx' ]);
            $(f).attr("enctype", "multipart/form-data");
            f.appendChild(i);
            document.body.appendChild(f);
            i.click();
        }
    
        /**
         *提交表单
         */
        function importData(actionUrl) {
            //同步提交
            //$("form[name='myFrom']").submit();
    
            //异步提交
            var nmiframe = document.forms['myFrom'];
            var formData = new FormData(nmiframe);
            $.ajax({
                url : actionUrl,
                type : 'POST',
                data : formData,
                async : false,
                cache : false,
                contentType : false,
                processData : false,
                success : function(returndata) {
                    alert(returndata);
                    window.location.reload(true);//重新加载页面
    
                },
                error : function(returndata) {
                    alert(returndata);
                }
            });
        }
    </script>

    java代码

     /**
         * @param request
         * @param response
         * @throws Exception
         *             执行导入操作
         */
        @RequestMapping("importExcel")
        public void importExcel(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
            String rq = request.getParameter("rq");
    
            // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            MultipartFile fileLoad = request.getFile("xmlFile");
            ResultMessage resultMessage = null;
    
            String result = "导入数据成功";
            try {
                String fileType = fileLoad.getOriginalFilename().substring(fileLoad.getOriginalFilename().lastIndexOf(".") + 1, fileLoad.getOriginalFilename().length());
                Workbook wb = null;
                if (fileType.equals("xls")) {
                    wb = new HSSFWorkbook(fileLoad.getInputStream());
                } else if (fileType.equals("xlsx")) {
                    wb = new XSSFWorkbook(fileLoad.getInputStream());
                } else {
                    throw new Exception("读取的不是excel文件");
                }
    
                this.importExcelHandle(request, wb);
    
                if (result.contains("成功")) {
                    resultMessage = new ResultMessage(ResultMessage.SUCCESS, "导入成功!");
                } else {
                    resultMessage = new ResultMessage(ResultMessage.FAIL, result);
                }
                writeResultMessage(response.getWriter(), resultMessage);
            } catch (Exception ex) {
                ex.printStackTrace();
                resultMessage = new ResultMessage(ResultMessage.FAIL, result);
                resultMessage.setMessage("导入失败--" + ex.getMessage());
                response.getWriter().print(resultMessage);
            }
        }
        
        
        /*
         * 具体导入操作
         * 
         * 
         */
        public void importExcelHandle(MultipartHttpServletRequest request, Workbook wb) throws Exception {
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            // 读取了模板内所有sheet内容
            HSSFSheet sheet = (HSSFSheet) wb.getSheetAt(0);
            HSSFCell cell = null;
    
            int physicalNumberOfRows = sheet.getLastRowNum();//指物理行数,并不是下标,即行数从1开始
    
          //String[] headers = {"序号","单位","机组","容量","开始","结束","工期","类型","发电类型"};
            String[] headersVar = {"xh","dw","jz","rl","ks","js","gq","lx","zt"};
            
            //把sheet内容转换成list
            
            List<Jzjxjh> list = new ArrayList<Jzjxjh>();
            // 遍历每一行,从第三行开始
            for (int i = 2; i <= physicalNumberOfRows; i++) {
                Jzjxjh  jzjxjh = new Jzjxjh();
                Object object = null;
                HSSFRow row = sheet.getRow(i);
                // 遍历每一列
                for (int j = 0; j < headersVar.length; j++) {
                    if(row!=null){
                        cell = row.getCell(j);
                        if(cell!=null){
                   
                         cell.setCellType(Cell.CELL_TYPE_STRING);
                         String colVal = cell.getStringCellValue();
    
                        if (StringUtil.isNotEmpty(colVal)) {
                             object = ReflectUtil.setValueBySetter(headersVar[j], jzjxjh, colVal,"yyyy/MM/dd");
                        }
                     }
                    }
                }
                Jzjxjh  e = (Jzjxjh) object;
                String id = UniqueIdUtil.getId();
                e.setId(id);
                e.setMyId(id);
                list.add(e);
            }
    
            //业务处理插入数据库
            for(Jzjxjh e:list){
                 
            }
            
        }
    其中 ReflectUtil工具类可到本博客util标签查找,注意下 上面代码表头和java类属性要一一对应
    导入的excel样例

  • 相关阅读:
    VUE3 使用 Ant Design Vue 图标库的图标
    Vue3 前端获取数据后 “响应式表示” ref and reactive
    Vue3 使用 生命周期函数
    SpringBoot 前后端分离 跨域小问题
    Vue 使用 Ant Design Vue 。
    SB + Mybatis generator 实现模糊查询 且 过滤数据返回体 + Bean转换
    springboot+mybatis 利用插件生成代码
    spark-sql-03从mysql获取数据上传数据
    spark-sql-02
    sprak-sql-01-基础
  • 原文地址:https://www.cnblogs.com/rdchen/p/14001373.html
Copyright © 2011-2022 走看看