java web項目中導入excel 到數據庫

數據庫中的表:

和javaBean中對應

javaBean:

public class mainpart {
 private int id;
 private String name;//名稱
 private String spid;
 private String specification;//規格
 private String suppid;
 private String suppname;//供應商名稱
 private String authenticatedMarks;//認證標誌
 private String standard;//標準
 private String parameter;//參數
 private Integer modelId;
 
 
 public Integer getModelId() {
  return modelId;
 }
 public void setModelId(Integer modelId) {
  this.modelId = modelId;
 }
 public String getAuthenticatedMarks() {
  return authenticatedMarks;
 }
 public void setAuthenticatedMarks(String authenticatedMarks) {
  this.authenticatedMarks = authenticatedMarks;
 }
 public String getStandard() {
  return standard;
 }
 public void setStandard(String standard) {
  this.standard = standard;
 }
 public String getParameter() {
  return parameter;
 }
 public void setParameter(String parameter) {
  this.parameter = parameter;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSpid() {
  return spid;
 }
 public void setSpid(String spid) {
  this.spid = spid;
 }
 public String getSpecification() {
  return specification;
 }
 public void setSpecification(String specification) {
  this.specification = specification;
 }
 public String getSuppid() {
  return suppid;
 }
 public void setSuppid(String suppid) {
  this.suppid = suppid;
 }
 public String getSuppname() {
  return suppname;
 }
 public void setSuppname(String suppname) {
  this.suppname = suppname;
 }

}


上傳調用:思想是讀取excel中的每一行數據,從第1行起(第0列爲表頭),每列的數據轉換爲string類型的,在通過sql語句

依次插入數據庫(插入,更新的兩個函數就不再貼出了)

public class MainPartimportBean {
private static Logger log = Logger.getLogger(SampleBean.class);
   public void insertDB(InputStream fp,String modelId) {
	  try {
		HSSFWorkbook workbook = new HSSFWorkbook(fp);// 創建工作薄
		HSSFSheet sheet = workbook.getSheetAt(0);// 得到工作表
		HSSFRow row = null;// 對應excel的行
		HSSFCell cell = null;// 對應excel的列
		String Var="";
		row = sheet.getRow((short)0);
	

		int totalRow = sheet.getLastRowNum();// 得到excel的總記錄條數
		    int modelId2 = Integer.valueOf(modelId);
			String name = "";//名稱
			String specification = "";//規格
			String suppname = "";//供應商名稱
			String parameter = "";//參數
			String standard = "";//標準
			String authenticatedMarks = "";//認證標誌
			
			
			for (short i = 1; i <=totalRow; i++) {
				mainBean mb = new mainBean();
				mainpart mp1 = new mainpart();
				row = sheet.getRow(i);
				cell = row.getCell((short)0);
				if(cell!=null)
				name = cell.getRichStringCellValue().toString();
				mp1.setName(name);
				
				cell = row.getCell((short)1);
				if(cell!=null)
				specification =cell.getRichStringCellValue().toString();
				mp1.setSpecification(specification);
				
				cell = row.getCell((short)2);
				if(cell!=null)
				suppname =  cell.getRichStringCellValue().toString();
				mp1.setSuppname(suppname);
				
				cell = row.getCell((short)3);
				if(cell!=null)
				parameter =  cell.getRichStringCellValue().toString();
				mp1.setParameter(parameter);
				
				cell = row.getCell((short)4);
				if(cell!=null)
				standard =  cell.getRichStringCellValue().toString();
				mp1.setStandard(standard);
				
				cell = row.getCell((short)5);
				if(cell!=null)
				authenticatedMarks =  cell.getRichStringCellValue().toString();
				mp1.setAuthenticatedMarks(authenticatedMarks);
				mp1.setModelId(modelId2);
				if(mb.isEmptymainpart(authenticatedMarks))
					mb.updataMainBymainpart(mp1);//防止數據重複
				else
				mb.newMainUpdata(mp1);//插入數據
			}
	
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}


	
	
}


jsp頁面:

a.jsp

  <script type="text/javascript">
  function imp(modelId){
    		 var form = document.getElementById("form1");
    		 form.setAttribute('method','post');
    		  if(form.encoding){
    		      form.setAttribute('encoding','multipart/form-data');
    		  }else{
    		      form.setAttribute('enctype','multipart/form-data');
    		  }
    		  form.setAttribute('action','<%=path%>/b.jsp?modelId='+modelId);
    		  form.submit();
        }
  	
  </script>
<body topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0 >
	<form id="form1" name="form1" >
		<br/>
       

		    <table width="750" border="0" align="center">
			
           <tr height="30">
            <td width="5%">
               <img src="<%=path%>/images/orgadd.gif"/>
            </td>
            <td width="10%">
             	<input type="file" id="f1" name="f1" style="position:absolute;filter:alpha(opacity=0);width:30px;" οnchange="imp(<%=modelId%>)"/>
		    	<input type="button" name="checkSAPmain" id="checkSAPmain" value="導入數據" Class="listLink"  >

            </td>
            <td align="left">
              <font Class="contentLabel">導入數據</font>
	
            </td>
           </tr>
          
	 
</body>
 

b.jsp:(先上傳了文件,在對文件進行處理,避免服務器和客戶端不是同一機器時出錯)

<html>
  <head>

    <title>My JSP 'dataSave.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <Script type="text/javascript">
  function onload(){
	  var existSub=document.getElementById("existSub").value;
	  str=window.encodeURI(existSub);
	  str=window.encodeURI(str);
	   var path="<%=basePath%>standard/stdDefault.jsp?existSub="+str;
	   self.location.href=path;
       self.parent.frames["sdtree"].location.href="<%=basePath%>standard/standTree.jsp";
     
      
   }
  </Script>
  

   <%
      String modelId = request.getParameter("modelId");
      MainPartimportBean mp =new MainPartimportBean();
      String existSub="";
     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     if (isMultipart) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(1024 * 10);

      // 設置存放臨時文件的目錄,web根目錄下的ImagesUploadTemp目錄
     // factory.setRepository(new File("f:\\test"));// 臨時文件

      // 用上面的工廠實例化上傳組件,
      ServletFileUpload upload = new ServletFileUpload(factory);

      // 設置最大上傳大小 10M
      upload.setSizeMax(1024*1024*10);
      String name = "";
      try {
       List items = upload.parseRequest(request); // 得到所有FileItem
       // 上傳文件的個數
       Iterator iter = items.iterator();
       // 循環處理所有文件
       while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        // 判斷是否是表單元素(<input type="text" />單選,多選等)
        if (!item.isFormField()) {
         // 得到文件的名稱
         name = item.getName();
         // 文件長度
         long size = item.getSize();// 過濾大小
         if (name == null || "".equals(name.trim())) {
          // 未選擇上傳文件
          continue;
         }
         // 以下爲文件名處理,將上傳的文件保存在項目所在目錄下。
         // 獲取文件名字符串的長度
         //int end = name.length();
         // 返回在此字符串中最右邊出現的指定子字符串的索引。
         int begin = name.lastIndexOf("\\");
         //int start = name.lastIndexOf(".");
         // 輸出上傳文件類型,此處可以進行類型的過濾
      	System.out.println(application.getRealPath("/js")+System.getProperty("file.separator")+name.substring(begin + 1));
        // File file = new File("f:\\"+name.substring(begin + 1, end));
        File file=new File(application.getRealPath("/js")+System.getProperty("file.separator")+name.substring(begin + 1));
         if (file.exists()) {
          file.delete();
         }
         item.write(file);
         
         
        ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); 
      	FileInputStream fis = new FileInputStream(file);  
     	byte[] by = new byte[512];  
     	int t = fis.read(by,0,by.length); 
     	 while(t>0){  
     		 byteOS.write(by, 0, 512);  //這裏別寫成t,寫夠512
      	     t = fis.read(by,0,by.length);  
     	} 
      	byteOS.close();  
         InputStream byteIS = new ByteArrayInputStream(byteOS.toByteArray()); 
         POIImportExcel pe=new POIImportExcel();
        mp.insertDB(byteIS,modelId);//只有這裏是調用了函數,其他地方都爲固定格式
         byteIS.close();
        
         file.delete();
         
         existSub="<script>alert('導入成功')</script>";	
        } 
       }

      } catch (FileUploadException e) {
       existSub="<script>alert('文件不能大於10M')</script>";	
       e.printStackTrace();
      } catch (Exception e) {
       // 處理文件寫入時的異常
       e.printStackTrace();
      }
     }
	     request.getRequestDispatcher("a.jsp").forward(request, response);
       
   %>
 
  <body οnlοad="javascript:onload();">
  <input type="hidden" id="existSub" value="<%=existSub%>">
  </body>
</html>



 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章