java实现Excel导入数据库

这是一个比较简单的例子,做的操作是选择角色,把用户的ID导入用户角色表(如何获取角色信息,就没在贴出来了)。用到了Struts2、jdbc。
需要jlx.jar 等几个必须的包。


 <%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib uri="http://www.ecside.org" prefix="ec"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    
    <title>excel</title>
     <%@include file="../inc/perm.inc"%>
	<script type="text/javascript">
		function myFormCheck(theform)
		{
			if(theform.roleid.value==""){
				alert("请选择对应的角色")
				return (false);
			}
		   if(theform.theFile.value=="")
		     {
		        alert("请点击浏览按钮,选择您要上传的文件!")
		        theform.theFile.focus;
		      	return (false);
		     }
		    else
		     {
		        str= theform.theFile.value;
		        strs=str.toLowerCase();
		        lens=strs.length;
		        extname=strs.substring(lens-4,lens);
		       if(extname!=".xls")
		        {
		          alert("请选择excel文件!")
		         return (false);
		        }
		      
		     }
		}
		
	</script>

  </head>
  
  <body>
    <center>
    <div style="position: absolute; left: 30%; top: 20%">
     导入信息
    </div>
    <div style="position: absolute; left: 30%; top: 30%">
     <form name="uploadform" action="<%=contextPath%>/features/excel.action" enctype="multipart/form-data" method=post onsubmit="return myFormCheck(this)">
  <SELECT name="roleid" id="select">
     		<OPTION value="" >----请选择----</OPTION>
			<s:iterator value="allRole">
				<OPTION value="${roleId}">${roleId}.${desc}</OPTION>
			</s:iterator>
		</SELECT>
		<input type="file" name="theFile">
	     <input type="submit" value="导入">
     </form>
    </div>
    </center>
  </body>
</html>


 <action name="excel" class="com.skyarm.action.FeaturesAction" method="uplode">
			<result>/success.jsp</result>
		</action>



public class FeaturesAction extends ActionSupport {
	private static final long serialVersionUID = -34341L;
//	private static final int BUFFER_SIZE = 16 * 1024;
	private File theFile;
	private String roleid;



	public String uplode(){
		int i = UplodeService.uplode(roleid,theFile);
		return SUCCESS;

	}
	
	
	
	public String getRoleid() {
		return roleid;
	}

	public void setRoleid(String roleid) {
		this.roleid = roleid;
	}

	public File getTheFile() {
		return theFile;
	}

	public void setTheFile(File theFile) {
		this.theFile = theFile;
	}	
}


  public class UplodeService {

	public static void uplode(String id,File file){
		int rows = 0; //表单行数

		Sheet sh = null; //表单对象
		InputStream inputStream = null;
		Workbook book = null;
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			inputStream = new FileInputStream(file);
			book = Workbook.getWorkbook(inputStream);
			sh = book.getSheet(0);
			rows = sh.getRows();
			conn = DataModule.getConnection();
			String sql = "INSERT INTO auth_user_role (userid,roleid) VALUES (?,?)";
			String userid;
			for(int i=0;i<rows;i++){ // 程序只取第一列
				userid = sh.getCell(0, i).getContents();
				//判断userid的合法性
//				if(5>userid.length() || 8<userid.length())
//					return 0;
				stmt = conn.prepareStatement(sql);
				stmt.setString(1, userid);
				stmt.setString(2, id);
				stmt.executeUpdate();
			}
			
				
		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (BiffException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();
	
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(inputStream!=null)
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(book!=null)
				book.close();
			
			DataModule.close(stmt);
			DataModule.close(conn);
		}
	}

}

你可能感兴趣的:(java,sql,jsp,struts,Excel)