easyui,springmvc,poi实现上传excel写入数据到数据库中

转自:https://blog.csdn.net/qq_20372833/article/details/79423083

上传excel文件操作数据有两种方式,分别是poi和jxl。但是jxl对高版本的excel(.xlsx)无法提供支持,所以本文使用poi实现。
前端使用easyui实现,控制层使用流行框架springmvc.

所需要的jar包:
poi-3.17jar,
poi-ooxml-3.17jar,
poi-ooxml-schemal-3.17jar,
xbean.jar


jsp代码:

<form id="indicatorAddExcelForm" method="post" enctype="multipart/form-data">
            <table class="grid">
              <tr>
                <td>请选择Excel文件</td>            
                <td><input type="file" class="easyui-validatebox" id="upfile" name="upfile"></td> 
                             
              </tr>             
            </table>  
        </form>
js代码:
注意:js代码主要是表明springmvc请求路径,其他代码可能是从项目里面拿出来的,仅作参考。前端页面以及js可参考其他。
<script type="text/javascript">
    $(function() 
    {
        $('#indicatorAddExcelForm').form(
        {
            url : '${pageContext.request.contextPath}/selfevaluation/addExcel',
            onSubmit : function() 
            {              
                progressLoad();
                var isValid = $(this).form('validate');
                if (!isValid) 
                {
                    progressClose();
                }
                return isValid;
            },
            success : function(result) 
            {                
                progressClose();
                result = $.parseJSON(result);            
                if (result.success) 
                {        
                    parent.$.messager.alert('成功', result.msg, 'info');          
                    parent.$.modalDialog.handler.dialog('close');
                } else 
                {
                    parent.$.messager.alert('错误', result.msg, 'error');
                }
            }
        });
    });
</script>
springmvc代码:
    @RequestMapping("/addExcel")
    @ResponseBody
    public Json addExcel(HttpSession session,HttpServletRequest request) 
    {
        List<Indicator> inds=new ArrayList<Indicator>();//创建保存数据的list
        Json jj = new Json();                
        try
        {                       
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
            //输入流  
            InputStream in =null;
            MultipartFile file = multipartRequest.getFile("upfile"); 
            if(file.isEmpty())
            {  
                jj.setSuccess(false);
                jj.setMsg("文件不存在!");
                return jj;
            }
            String filename=file.getOriginalFilename();
            in = file.getInputStream(); 
            //得到excel  
            Workbook wb = null;
            String fileType = filename.substring(filename.lastIndexOf("."));  
            if((".xls").equals(fileType))
            {  
                wb = new HSSFWorkbook(in);  //2003-  
            }else if((".xlsx").equals(fileType))
            {  
               wb = new XSSFWorkbook(in);  //2007+  
            }else
            {  
                jj.setSuccess(false);
                jj.setMsg("文件格式错误!");
                return jj;
            }             
            //得到sheet  
            Sheet sheet = wb.getSheetAt(0); //默认取第一个sheet              
            //int colsNum = sheet.getPhysicalNumberOfRows();  //获取实际的行数           
            int rowsNum = sheet.getLastRowNum();//                            
            for(int j=1; j<rowsNum+1;j++) //第一行为表头,所以从第二行开始
            {// getLastRowNum,获取最后一行的行标
                Row row =sheet.getRow(j);
                if (row != null) 
                {
                    Indicator ind=new Indicator();
                    ind.setIndicator_itemid(row.getCell(0).toString());
                    ind.setDept_result(row.getCell(1).toString());
                    ind.setDept_remark(row.getCell(2).toString());
                    inds.add(ind);
                    /*for (int k = 0; k < row.getLastCellNum(); k++) 
                    {// getLastCellNum,是获取最后一个不为空的列是第几个                           
                        System.out.print(row.getCell(k) + "\t");                          
                    }*/
                }
                      
            }
            //System.out.println(inds);
            wb.close();      
         } catch (IOException e) 
         {  
              e.printStackTrace();  
         }
        //获取登陆用户的id
        SessionInfo sessionInfo=(SessionInfo)session.getAttribute(GlobalConstant.SESSION_INFO);
        selfEvaluationService.addExcel(sessionInfo.getId(),inds);
        jj.setSuccess(true);
        jj.setMsg("添加成功!");
        return jj;
    }


最后,别忘了在spring-mvc.xml文件中加入配置,如果已经配置过,忽略即可。
<!-- 上传文件控制 -->
<bean id="multipartResolver"  
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 设置上传文件的最大尺寸为10MB -->  
    <property name="maxUploadSize">  
        <value>10485760</value>  
    </property> 
     
</bean>

--------------------- 
作者:笑*容 
来源:CSDN 
原文:https://blog.csdn.net/qq_20372833/article/details/79423083 
版权声明:本文为博主原创文章,转载请附上博文链接!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值