把EXCEL用程序导入到ORACLE中(SpringMVC+MyBatis)

id="cpro_u2392861_iframe" src="http://pos.baidu.com/xcsm?sz=300x250&rdid=2392861&dc=2&di=u2392861&dri=0&dis=0&dai=1&ps=589x1020&coa=at%3D3%26rsi0%3D300%26rsi1%3D250%26pat%3D17%26tn%3DbaiduCustNativeAD_xuanfu%26rss1%3D%2523FFFFFF%26conBW%3D1%26adp%3D1%26ptt%3D0%26titFF%3D%2525E5%2525BE%2525AE%2525E8%2525BD%2525AF%2525E9%25259B%252585%2525E9%2525BB%252591%26titFS%3D14%26rss2%3D%2523000000%26titSU%3D0&dcb=BAIDU_SSP_define&dtm=BAIDU_DUP_SETJSONADSLOT&dvi=0.0&dci=-1&dpt=none&tsr=0&tpr=1466487340982&ti=%E6%8A%8AEXCEL%E7%94%A8%E7%A8%8B%E5%BA%8F%E5%AF%BC%E5%85%A5%E5%88%B0ORACLE%E4%B8%AD(SpringMVC%2BMyBatis)%20-%20zlxdream815%E7%9A%84%E4%B8%93%E6%A0%8F%20-%20%E5%8D%9A%E5%AE%A2&ari=1&dbv=2&drs=3&pcs=1031x600&pss=1170x11769&cfv=11&cpl=17&chi=2&cce=true&cec=UTF-8&tlm=1466458540&ltu=http%3A%2F%2Fblog.csdn.net%2Fzlxdream815%2Farticle%2Fdetails%2F41086995&ecd=1&psr=1366x768&par=1366x728&pis=-1x-1&ccd=24&cja=true&cmi=23&col=zh-CN&cdo=-1&tcn=1466487341&qn=bad35b3bd01008c3&tt=1466487340962.24.251.254" width="300" height="250" align="center,center" vspace="0" hspace="0" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" style="border:0; vertical-align:bottom;margin:0;" allowtransparency="true">
关闭
href="http://static.blog.csdn.net/css/comment1.css" type="text/css" rel="stylesheet" /> href="http://static.blog.csdn.net/css/style1.css" type="text/css" rel="stylesheet" /> rel="stylesheet" href="http://static.blog.csdn.net/public/res-min/markdown_views.css?v=1.0" /> rel="stylesheet" href="http://static.blog.csdn.net/css/category.css?v=1.0" /> rel="stylesheet" href="http://static.blog.csdn.net/css/blog_code.css" />

把EXCEL用程序导入到ORACLE中(SpringMVC+MyBatis)

3346人阅读 评论(1) 收藏 举报
分类:
  1.   

前提:项目中需要把EXCEL数据批量导入oracle中两张表中。如是用到了poi技术。分别导入poi-3.11-beta2.jar和poi-ooxml-schemas-3.9.jar这两个包。EXCEL数据如下


第一步:修改spring框架配置文件。 springmvc-servlet.xml加上:

 <!-- 文件上传 -->
       <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  p:defaultEncoding="utf-8" /> 


第一步:添加页面jsp。view_user_batchadd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%  
String importMsg="";  
if(request.getSession().getAttribute("msg")!=null){  
importMsg=request.getSession().getAttribute("msg").toString();  
}  
request.getSession().setAttribute("msg", "");  
%>
<head>
    <title>批量导入用户</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <script type="text/javascript" src="<%=request.getContextPath()%>/view/js/jquery.js"></script>
<body>
    <form action="<%=request.getContextPath()%>/manager/index/batchimport" method="post" enctype="multipart/form-data" name="batchAdd" onsubmit="return check();">
        <div style="margin: 30px;"><input id="excel_file" type="file" name="filename" accept="xls" size="50"/>
        <div><input id="excel_file" type="file" name="filename"  size="50"/>
        <input id="excel_button" type="submit" value="导入Excel"/></div>
        <font id="importMsg" color="red"><%=importMsg%></font><input type="hidden"/>  
    </form>
</body>
<script type="text/javascript">
    function check() {  
     var excel_file = $("#excel_file").val();  
     if (excel_file == "" || excel_file.length == 0) {  
         alert("请选择文件路径!");  
         return false;  
     } else {  
        return true;  
    }  
}
    
    $(document).ready(function () {  
          var msg="";  
          if($("#importMsg").text()!=null){  
                
              msg=$("#importMsg").text();  
          }  
          if(msg!=""){  
              alert(msg);  
          }  
        });  
</script>
</html>

第三步:填写控制器:UserLoginController.Java

/**
 * 2014-8-30 下午2:52:49
 * TODO  用户登录 Controller
 *
 */
@Controller
@RequestMapping("/index")
public class UserLoginController  {
    private Log log = LogFactory.getLog(UserLoginController.class);
    
    @Autowired
    private UserLoginService userLoginService;
    
    @Autowired
    private UserInfoService userInfoService;
    
    @RequestMapping(value = "/batchimport", method = RequestMethod.POST)
    public ModelAndView batchimport(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{
        log.info("UserLoginController ..batchimport() start");
        //判断文件名是否为空
        if(file==null) return null;
        
        //获取文件名
        String name=file.getOriginalFilename();
        
        //判断文件大小、即名称
        long size=file.getSize();
        if(name==null || ("").equals(name) && size==0) return null;
        
        try {
            //把文件转换成字节流形式
            InputStream in = file.getInputStream();
            int i=userLoginService.batchImport(name,file);
            int j=userInfoService.batchImport(name,file);
            if(i>0 && j>0){
                 String Msg ="批量导入EXCEL成功!";
                 request.getSession().setAttribute("msg",Msg);    
            }else{
                 String Msg ="批量导入EXCEL失败!";
                 request.getSession().setAttribute("msg",Msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
}

注:我这个Controller的方法里面处理了两个接口实现类。我这里就写一个

第三步:实现类:UserLoginServiceImpl.java

public int batchImport(String name,MultipartFile file) throws Exception {

        //处理EXCEL
        ReadExcel readExcel=new ReadExcel();
        //获得解析excel方法
        List<User> userList=readExcel.getExcelInfo(name,file);
        
        //把excel信息添加到数据库
        List<UserLogin> LoginList=new ArrayList<UserLogin>();
        
        for(User user:userList){
            LoginList.add(user.getUserLogin());
        }
        return userLoginDao.saveBatch(LoginList);//添加登录信息
    }


第四步:处理EXCEL类:ReadExcel.java

public class ReadExcel {
    
      //总行数
      private int totalRows = 0;  
    
      //总条数
      private int totalCells = 0;
      
      //错误信息接收器
      private String errorMsg;
            
      //构造方法
      public ReadExcel(){}
      
      //得到总行数
      public int getTotalRows()  { return totalRows;}
      
      //得到总列数
      public int getTotalCells() {  return totalCells;}
      
      public String getErrorInfo() { return errorMsg; }  
      
    /**
     * 描述:验证EXCEL文件
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath){
          if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){  
              errorMsg = "文件名不是excel格式";  
              return false;  
          }  
          return true;
    }
      
    
    /**描述 :读EXCEL文件
     * @param fielName
     * @return
     */
    public List<User> getExcelInfo(String fileName,MultipartFile Mfile){
        
        //把spring文件上传的MultipartFile转换成File
         CommonsMultipartFile cf= (CommonsMultipartFile)Mfile;
         DiskFileItem fi = (DiskFileItem)cf.getFileItem();
         File file = fi.getStoreLocation();
        
        List<User> userList=new ArrayList<User>();
        InputStream is = null;  
        try{
            //验证文件名是否合格
            if(!validateExcel(fileName)){
                return null;
            }
            //判断文件时2003版本还是2007版本
            boolean isExcel2003 = true;
            if(WDWUtil.isExcel2007(fileName)){
                isExcel2003 = false;  
            }
            is = new FileInputStream(file);
            userList=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 userList;
    }
    /**
     * 此方法两个参数InputStream是字节流。isExcel2003是excel是2003还是2007版本
     * @param is
     * @param isExcel2003
     * @return
     * @throws IOException
     */
    public  List<User> getExcelInfo(InputStream is,boolean isExcel2003){
        
         List<User> userList=null;
         try{
             /** 根据版本选择创建Workbook的方式 */
             Workbook wb = null;
             //当excel是2003时
             if(isExcel2003){
                 wb = new HSSFWorkbook(is);
             }
             else{
                 wb = new XSSFWorkbook(is);
             }
             userList=readExcelValue(wb);
         }
         catch (IOException e)  {  
             e.printStackTrace();  
         }  
         return userList;
    }
    /**
     * 读取Excel里面的信息
     * @param wb
     * @return
     */
    private List<User> 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<User> userList=new ArrayList<User>();
         User user;            //用户bean(组成:UserInfo+UserLogin)
         UserInfo userInfo; //用户基本信息bean
         UserLogin userLogin;    //用户登录bean
        
         //循环Excel行数,从第二行开始。标题不入库
         for(int r=1;r<totalRows;r++)
         {
             Row row = sheet.getRow(r);
             if (row == null) continue;
            
             user=new User();
             userInfo=new UserInfo();
             userLogin=new UserLogin();
            
             //循环Excel的列
             for(int c = 0; c <this.totalCells; c++)
             {    
                 Cell cell = row.getCell(c);
                 if (null != cell)  
                 {
                     //第一列
                     if(c==0){
                         //获得第一列<用户名>,放到到用户基本信息bean中。
                        userInfo.setUserName(cell.getStringCellValue());
                     }
                     //获得第二列<手机号>,放到到用户登录bean中。作为登录账号及密码
                     else if(c==1){
                         /**
                          * 处理:使用POI读excel文件,当遇到特殊格式的字串,比如“13612345678”,等等,
                          * 这样的本来是一个字符串,但是POI在读的时候总是以数值型识别,由此,这样的电话号码读出来后总是1.3XXX+E4

                          */
                        DecimalFormat df = new DecimalFormat("#");
                        String cellValue=df.format(cell.getNumericCellValue());
                         userLogin.setAccount(cellValue);
                         userLogin.setPwd(cellValue);
                    
                         
                     }
                     //第三列目前不入库,只是展示即可

                     //第四列<用户地址>,放到到用户基本信息bean中。
                     else if(c==3){
                        userInfo.setCompanyAdd(cell.getStringCellValue());
                     }
                 }
             }
             //添加其他值,入库时需要
             userLogin.setUserId(Utils.getzId());//存放用户ID
             userLogin.setInsertTime(Utils.getshortDate());//注册时间
             userLogin.setUserRole("2"); //默认导入的用户都为供应商级别
            
             userInfo.setUserInfoid(Utils.getzId());//存放用户ID
             userInfo.setUserId(userLogin.getUserId());//基本信息的用户ID
            
             user.setUserInfo(userInfo);
             user.setUserLogin(userLogin);
            
             userList.add(user);
         }
         return userList;
    }
}
/**  
 * @描述:工具类
 * 检验是否是EXCEL文件
 */   
class WDWUtil  
{  
     // @描述:是否是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)$");  
    }  
}




<script>window._bd_share_config = { "common": { "bdsnskey": {}, "bdtext": "", "bdmini": "1", "bdminilist": false, "bdpic": "", "bdstyle": "0", "bdsize": "16" }, "share": {} }; with (document) 0[(getelementsbytagname('head')[0] || body).appendchild(createelement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new date() / <script type="text/javascript" id="bdshare_js" data="type=tools&amp;uid=1536434" src="http://bdimg.share.baidu.com/static/j<script type="text/javascript">document.getelementbyid("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + math.ceil(new date()/3600000)</script>m/static/js/bds_s_v2.js?cdnversion=407358">
1
0
 
 
我的同类文章
rel="stylesheet" href="http://static.blog.csdn.net/css/replace.css" />

参考知识库

img
jQuery知识库

img
JavaScript知识库

img
AngularJS知识库

img
Java EE知识库

img
MySQL知识库

img
Java SE知识库

img
Java Web知识库

猜你在找
width="728" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" onload="var i=this.id,s=window.google_iframe_oncopy,H=s&&s.handlers,h=H&&H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&&d&&(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;">
查看评论
1楼 sunzhuang 2016-06-11 15:41发表 [回复]
大神,请问 您的源码还在吗?跪求参考。。。。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
  • 个人资料
    • 访问:59662次
    • 积分:960
    • 等级:
    • 排名:千里之外
    • 原创:36篇
    • 转载:6篇
    • 译文:1篇
    • 评论:5条
  • 文章分类
  • 最新评论
rel="stylesheet" type="text/css" href="//csdnimg.cn/pubfooter/css/pub_footer_2014.css" />
href="http://c.csdnimg.cn/comm_ask/css/ask_float_block.css" type="text/css" rel="stylesheet" />
rel="stylesheet" type="text/css" media="screen" href="http://ask.csdn.net/assets/ask_float_fonts_css-6b30a53970eb5c3a2a045e3df585b475.css" />

提问

您的问题将会被发布在“技术问答”频道 ×
该问题已存在,请勿重复提问
src="http://ask.csdn.net/upload.html">
插入图片
| | | | | |
  
 
 
0 0 0:0
推荐标签:
我要悬赏
取消 发布
可能存在类似的问题:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值