分享

java web项目中导入excel 到数据库

 Bladexu的文库 2017-11-29

数据库中的表:

和javaBean中对应

javaBean:

  1. public class mainpart {  
  2.  private int id;  
  3.  private String name;//名称  
  4.  private String spid;  
  5.  private String specification;//规格  
  6.  private String suppid;  
  7.  private String suppname;//供应商名称  
  8.  private String authenticatedMarks;//认证标志  
  9.  private String standard;//标准  
  10.  private String parameter;//参数  
  11.  private Integer modelId;  
  12.    
  13.    
  14.  public Integer getModelId() {  
  15.   return modelId;  
  16.  }  
  17.  public void setModelId(Integer modelId) {  
  18.   this.modelId = modelId;  
  19.  }  
  20.  public String getAuthenticatedMarks() {  
  21.   return authenticatedMarks;  
  22.  }  
  23.  public void setAuthenticatedMarks(String authenticatedMarks) {  
  24.   this.authenticatedMarks = authenticatedMarks;  
  25.  }  
  26.  public String getStandard() {  
  27.   return standard;  
  28.  }  
  29.  public void setStandard(String standard) {  
  30.   this.standard = standard;  
  31.  }  
  32.  public String getParameter() {  
  33.   return parameter;  
  34.  }  
  35.  public void setParameter(String parameter) {  
  36.   this.parameter = parameter;  
  37.  }  
  38.  public int getId() {  
  39.   return id;  
  40.  }  
  41.  public void setId(int id) {  
  42.   this.id = id;  
  43.  }  
  44.  public String getName() {  
  45.   return name;  
  46.  }  
  47.  public void setName(String name) {  
  48.   this.name = name;  
  49.  }  
  50.  public String getSpid() {  
  51.   return spid;  
  52.  }  
  53.  public void setSpid(String spid) {  
  54.   this.spid = spid;  
  55.  }  
  56.  public String getSpecification() {  
  57.   return specification;  
  58.  }  
  59.  public void setSpecification(String specification) {  
  60.   this.specification = specification;  
  61.  }  
  62.  public String getSuppid() {  
  63.   return suppid;  
  64.  }  
  65.  public void setSuppid(String suppid) {  
  66.   this.suppid = suppid;  
  67.  }  
  68.  public String getSuppname() {  
  69.   return suppname;  
  70.  }  
  71.  public void setSuppname(String suppname) {  
  72.   this.suppname = suppname;  
  73.  }  
  74.   
  75. }  


上传调用:思想是读取excel中的每一行数据,从第1行起(第0列为表头),每列的数据转换为string类型的,在通过sql语句

依次插入数据库(插入,更新的两个函数就不再贴出了)

  1. public class MainPartimportBean {  
  2. private static Logger log = Logger.getLogger(SampleBean.class);  
  3.    public void insertDB(InputStream fp,String modelId) {  
  4.       try {  
  5.         HSSFWorkbook workbook = new HSSFWorkbook(fp);// 创建工作薄  
  6.         HSSFSheet sheet = workbook.getSheetAt(0);// 得到工作表  
  7.         HSSFRow row = null;// 对应excel的行  
  8.         HSSFCell cell = null;// 对应excel的列  
  9.         String Var="";  
  10.         row = sheet.getRow((short)0);  
  11.       
  12.   
  13.         int totalRow = sheet.getLastRowNum();// 得到excel的总记录条数  
  14.             int modelId2 = Integer.valueOf(modelId);  
  15.             String name = "";//名称  
  16.             String specification = "";//规格  
  17.             String suppname = "";//供应商名称  
  18.             String parameter = "";//参数  
  19.             String standard = "";//标准  
  20.             String authenticatedMarks = "";//认证标志  
  21.               
  22.               
  23.             for (short i = 1; i <=totalRow; i++) {  
  24.                 mainBean mb = new mainBean();  
  25.                 mainpart mp1 = new mainpart();  
  26.                 row = sheet.getRow(i);  
  27.                 cell = row.getCell((short)0);  
  28.                 if(cell!=null)  
  29.                 name = cell.getRichStringCellValue().toString();  
  30.                 mp1.setName(name);  
  31.                   
  32.                 cell = row.getCell((short)1);  
  33.                 if(cell!=null)  
  34.                 specification =cell.getRichStringCellValue().toString();  
  35.                 mp1.setSpecification(specification);  
  36.                   
  37.                 cell = row.getCell((short)2);  
  38.                 if(cell!=null)  
  39.                 suppname =  cell.getRichStringCellValue().toString();  
  40.                 mp1.setSuppname(suppname);  
  41.                   
  42.                 cell = row.getCell((short)3);  
  43.                 if(cell!=null)  
  44.                 parameter =  cell.getRichStringCellValue().toString();  
  45.                 mp1.setParameter(parameter);  
  46.                   
  47.                 cell = row.getCell((short)4);  
  48.                 if(cell!=null)  
  49.                 standard =  cell.getRichStringCellValue().toString();  
  50.                 mp1.setStandard(standard);  
  51.                   
  52.                 cell = row.getCell((short)5);  
  53.                 if(cell!=null)  
  54.                 authenticatedMarks =  cell.getRichStringCellValue().toString();  
  55.                 mp1.setAuthenticatedMarks(authenticatedMarks);  
  56.                 mp1.setModelId(modelId2);  
  57.                 if(mb.isEmptymainpart(authenticatedMarks))  
  58.                     mb.updataMainBymainpart(mp1);//防止数据重复  
  59.                 else  
  60.                 mb.newMainUpdata(mp1);//插入数据  
  61.             }  
  62.       
  63.     } catch (IOException e) {  
  64.         // TODO Auto-generated catch block  
  65.         e.printStackTrace();  
  66.     }  
  67.   
  68. }  
  69.   
  70.   
  71.       
  72.       
  73. }  


jsp页面:

a.jsp

  1. <script type="text/javascript">  
  2. function imp(modelId){  
  3.          var form = document.getElementById("form1");  
  4.          form.setAttribute('method','post');  
  5.           if(form.encoding){  
  6.               form.setAttribute('encoding','multipart/form-data');  
  7.           }else{  
  8.               form.setAttribute('enctype','multipart/form-data');  
  9.           }  
  10.           form.setAttribute('action','<%=path%>/b.jsp?modelId='+modelId);  
  11.           form.submit();  
  12.       }  
  13.       
  14. </script>  
  1. <body topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0 >  
  2.     <form id="form1" name="form1" >  
  3.         <br/>  
  4.          
  5.   
  6.             <table width="750" border="0" align="center">  
  7.               
  8.            <tr height="30">  
  9.             <td width="5%">  
  10.                <img src="<%=path%>/images/orgadd.gif"/>  
  11.             </td>  
  12.             <td width="10%">  
  13.                 <input type="file" id="f1" name="f1" style="position:absolute;filter:alpha(opacity=0);width:30px;" onchange="imp(<%=modelId%>)"/>  
  14.                 <input type="button" name="checkSAPmain" id="checkSAPmain" value="导入数据" Class="listLink"  >  
  15.   
  16.             </td>  
  17.             <td align="left">  
  18.               <font Class="contentLabel">导入数据</font>  
  19.       
  20.             </td>  
  21.            </tr>  
  22.             
  23.        
  24. </body>  
  1.    

b.jsp:(先上传了文件,在对文件进行处理,避免服务器和客户端不是同一机器时出错)

  1. <html>  
  2.   <head>  
  3.   
  4.     <title>My JSP 'dataSave.jsp' starting page</title>  
  5.       
  6.     <meta http-equiv="pragma" content="no-cache">  
  7.     <meta http-equiv="cache-control" content="no-cache">  
  8.     <meta http-equiv="expires" content="0">      
  9.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  10.     <meta http-equiv="description" content="This is my page">  
  11.     <!-- 
  12.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  13.     -->  
  14.   
  15.   </head>  
  16.   <Script type="text/javascript">  
  17.   function onload(){  
  18.       var existSub=document.getElementById("existSub").value;  
  19.       str=window.encodeURI(existSub);  
  20.       str=window.encodeURI(str);  
  21.        var path="<%=basePath%>standard/stdDefault.jsp?existSub="+str;  
  22.        self.location.href=path;  
  23.        self.parent.frames["sdtree"].location.href="<%=basePath%>standard/standTree.jsp";  
  24.        
  25.         
  26.    }  
  27.   </Script>  
  28.     
  29.   
  30.    <%  
  31.       String modelId = request.getParameter("modelId");  
  32.       MainPartimportBean mp =new MainPartimportBean();  
  33.       String existSub="";  
  34.      boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  35.      if (isMultipart) {  
  36.       DiskFileItemFactory factory = new DiskFileItemFactory();  
  37.       factory.setSizeThreshold(1024 * 10);  
  38.   
  39.       // 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录  
  40.      // factory.setRepository(new File("f:\\test"));// 临时文件  
  41.   
  42.       // 用上面的工厂实例化上传组件,  
  43.       ServletFileUpload upload = new ServletFileUpload(factory);  
  44.   
  45.       // 设置最大上传大小 10M  
  46.       upload.setSizeMax(1024*1024*10);  
  47.       String name = "";  
  48.       try {  
  49.        List items = upload.parseRequest(request); // 得到所有FileItem  
  50.        // 上传文件的个数  
  51.        Iterator iter = items.iterator();  
  52.        // 循环处理所有文件  
  53.        while (iter.hasNext()) {  
  54.         FileItem item = (FileItem) iter.next();  
  55.         // 判断是否是表单元素(<input type="text" />单选,多选等)  
  56.         if (!item.isFormField()) {  
  57.          // 得到文件的名称  
  58.          name = item.getName();  
  59.          // 文件长度  
  60.          long size = item.getSize();// 过滤大小  
  61.          if (name == null || "".equals(name.trim())) {  
  62.           // 未选择上传文件  
  63.           continue;  
  64.          }  
  65.          // 以下为文件名处理,将上传的文件保存在项目所在目录下。  
  66.          // 获取文件名字符串的长度  
  67.          //int end = name.length();  
  68.          // 返回在此字符串中最右边出现的指定子字符串的索引。  
  69.          int begin = name.lastIndexOf("\\");  
  70.          //int start = name.lastIndexOf(".");  
  71.          // 输出上传文件类型,此处可以进行类型的过滤  
  72.         System.out.println(application.getRealPath("/js")+System.getProperty("file.separator")+name.substring(begin + 1));  
  73.         // File file = new File("f:\\"+name.substring(begin + 1, end));  
  74.         File file=new File(application.getRealPath("/js")+System.getProperty("file.separator")+name.substring(begin + 1));  
  75.          if (file.exists()) {  
  76.           file.delete();  
  77.          }  
  78.          item.write(file);  
  79.            
  80.            
  81.         ByteArrayOutputStream byteOS = new ByteArrayOutputStream();   
  82.         FileInputStream fis = new FileInputStream(file);    
  83.         byte[] by = new byte[512];    
  84.         int t = fis.read(by,0,by.length);   
  85.          while(t>0){    
  86.              byteOS.write(by, 0, 512);  //这里别写成t,写够512  
  87.              t = fis.read(by,0,by.length);    
  88.         }   
  89.         byteOS.close();    
  90.          InputStream byteIS = new ByteArrayInputStream(byteOS.toByteArray());   
  91.          POIImportExcel pe=new POIImportExcel();  
  92.         mp.insertDB(byteIS,modelId);//只有这里是调用了函数,其他地方都为固定格式  
  93.          byteIS.close();  
  94.           
  95.          file.delete();  
  96.            
  97.          existSub="<script>alert('导入成功')</script>";   
  98.         }   
  99.        }  
  100.   
  101.       } catch (FileUploadException e) {  
  102.        existSub="<script>alert('文件不能大于10M')</script>";    
  103.        e.printStackTrace();  
  104.       } catch (Exception e) {  
  105.        // 处理文件写入时的异常  
  106.        e.printStackTrace();  
  107.       }  
  108.      }  
  109.          request.getRequestDispatcher("a.jsp").forward(request, response);  
  110.          
  111.    %>  
  112.    
  113.   <body onload="javascript:onload();">  
  114.   <input type="hidden" id="existSub" value="<%=existSub%>">  
  115.   </body>  
  116. </html>  



 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约