当前位置: 代码迷 >> Web前端 >> SSI兑现 excel 与ORACLE 之间的导入导出
  详细解决方案

SSI兑现 excel 与ORACLE 之间的导入导出

热度:626   发布时间:2012-06-27 14:20:08.0
SSI实现 excel 与ORACLE 之间的导入导出

1.导入相应的jar包

?

jxl.jar
antlr-2.7.2.jar
commons-collections.jar
commons-dbcp.jar
commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ibatis-2.3.4.726.jar
ognl-2.6.11.jar
spring.jar
struts2-core-2.0.14.jar
struts2-spring-plugin-2.0.14.jar
xwork-2.0.7.jar
ojbc14.jar

?

2.页面用freemerk

?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户管理</title>

<script>
  function interExcel(){
     window.location.href="interExcel.action"
  }
  
  function goExcelToOracle(){
     window.location.href="goExcelToOracle.action"
  }
</script>
</head>
<body>
   <form>
   <table>
   <tr><td>ID</td><td>姓名</td><td>密码</td></tr><br />
   <#list list?if_exists as user>
      <tr><td>${user.id}</td><td>${user.userName}</td><td>${user.password}</td></tr>
   </#list>
   
   <tr><td><input type="button" onclick="interExcel()" value="导入到Excel表中"/></td></tr>
   <tr><td><input type="button" onclick="goExcelToOracle()" value="Excel导入Oracle数据库"/></td></tr>
   </table>
   
   </form>
</body>
</html>

?

3. web.xml的配置

?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>excel</display-name>
  <welcome-file-list>
    <welcome-file>user.jsp</welcome-file>
  </welcome-file-list>
   <context-param>
      <param-name>contextConfigLocation</param-name>
 	  <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <filter>
     <filter-name>struts</filter-name>
     <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  
  <filter-mapping>
     <filter-name>struts</filter-name>
     <url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

?

4.struts.xml的配置

?

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 
    <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory"/>
    
    <package name="user" extends="struts-default" namespace="/">
    
        <action name="getAllUser" class="userAction" method="getAllUser">
            <result name="success" type="freemarker">WEB-INF/user.ftl</result>
        </action>
     
     <!-- 数据导入到Excel -->   
        <action name="interExcel" class="userAction" method="interExcel">
            <result name="success" type="freemarker">
                /WEB-INF/user.ftl
            </result>
            <result name="error" type="freemarker">
               /WEB-INF/error.ftl
            </result>
        </action>
     <!-- 数据从Excel导入Oracle数据库表中 -->   
        <action name="goExcelToOracle" class="userAction" method="goExcelToOracle">
              <result name="success" type="freemarker">
                   /WEB-INF/user.ftl
              </result>
        </action>
    </package>
    
  
</struts>

?

5.applicationContext.xml的配置

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    <bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>file:${global.config.path}jdbc_user_zhaoyun.properties</value>
			</list>
		</property>
	</bean>

	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName">
			<value>${jdbc.driverClassName}</value>
		</property>
		<property name="url">
			<value>${jdbc.url}</value>
		</property>
		<property name="username">
			<value>${jdbc.username}</value>
		</property>
		<property name="password">
			<value>${jdbc.password}</value>
		</property>
	</bean>


	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="configLocation">
			<value>classpath:sql-map-config.xml</value>
		</property>
	</bean>
     <!-- 本地服务对象 -->
	<bean id="userDao" class="com.daizhaoyun.dao.UserDaoImpl">
		<property name="client">
			<ref bean="sqlMapClient" />
		</property>
	</bean>
	<bean id="userService" class="com.daizhaoyun.service.UserServiceImpl">
		<property name="userDao">
			<ref bean="userDao" />
		</property>
	</bean>
	<bean id="userAction" class="com.daizhaoyun.action.UserAction">
		<property name="userService">
			<ref bean="userService" />
		</property>
	</bean>
	 
</beans>

?

6.jdbc_user_zhaoyun.properties 属性文件

?

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@192.168.129.12:1521:SID
#jdbc.username=test
#jdbc.password=aixs3GKgn4oVplJGeAI96Q..
jdbc.url=jdbc:oracle:thin:@192.168.129.12:1521:SID
jdbc.username=test
jdbc.password=test
jdbc.initialSize=1
jdbc.maxActive=2
jdbc.maxIdle=1
jdbc.defaultAutoCommit=true
jdbc.maxWait=5000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=180
	

?

7.sql-map-config.xml的配置

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

    <settings enhancementEnabled="true" maxTransactions="40" maxRequests="32" maxSessions="10"/>

<!-- sqlmap映射文件  处理相应的sql操作-->
    <sqlMap resource="sqlmap-user.xml"/>

</sqlMapConfig>

?

8.sqlmap-user.xml的配置

?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap>
  <!-- 类型映射 -->
   <typeAlias alias="user" type="com.daizhaoyun.dto.User"/>
   <resultMap id="MenuResult" class="com.daizhaoyun.dto.User" >
    <result column="ID" property="id"  />
    <result column="USERNAME" property="userName"  />
    <result column="PASSWORD" property="password"  />
  </resultMap>
   
   <select id="getAllUser" resultClass="user">
        select * from user_zhaoyun
   </select>
   
   <insert id="insertUser" parameterClass="user">
       insert into user_zhaoyun(id,username,password) values(#id#,#userName#,#password#)
   </insert>
   
</sqlMap>

?9.Dto

?

package com.daizhaoyun.dto;

public class User {
	
	private Integer id;
    private String userName;
    private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
    

}

?10.DAO

package com.daizhaoyun.dao;

import java.util.List;

import com.daizhaoyun.dto.User;

public interface UserDao {
	
	public List<User> getAllUser();
	
    public void insertUser(User user);
}
?
package com.daizhaoyun.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.daizhaoyun.dto.User;
import com.ibatis.sqlmap.client.SqlMapClient;

public class UserDaoImpl implements UserDao {
	
	SqlMapClient client;

	public SqlMapClient getClient() {
		return client;
	}

	public void setClient(SqlMapClient client) {
		this.client = client;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAllUser() {
		List<User> list = new ArrayList<User>();
		try {
			list = client.queryForList("getAllUser");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void insertUser(User user) {
        try {
        	//事务的开启
        	client.startTransaction();
			client.insert("insertUser", user);
			client.commitTransaction();
			client.endTransaction();
		} catch (SQLException e) {
			e.printStackTrace();
		}		
	}

}

?11.SERVICE

?

package com.daizhaoyun.service;

import java.util.List;

import com.daizhaoyun.dto.User;

public interface UserService {
	public List<User> getAllUser();
	public void insertUser(User user);
}
?
package com.daizhaoyun.service;

import java.util.List;

import com.daizhaoyun.dao.UserDao;
import com.daizhaoyun.dto.User;

public class UserServiceImpl implements UserService {
	
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public List<User> getAllUser() {
		return userDao.getAllUser();
	}

	@Override
	public void insertUser(User user) {
        userDao.insertUser(user);		
	}

}

?12.ACTION

package com.daizhaoyun.action;

import java.util.ArrayList;
import java.util.List;

import com.daizhaoyun.dto.User;
import com.daizhaoyun.service.UserService;
import com.daizhaoyun.tools.ExcelOpt;
import com.daizhaoyun.tools.GoToOracle;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UserAction extends ActionSupport {
	private UserService userService;
	private List<User> list;
	private User user;
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	public List<User> getList() {
		return list;
	}

	public void setList(List<User> list) {
		this.list = list;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 系统入口
	 */
	public String getAllUser(){
		list = userService.getAllUser();
		return SUCCESS;
	}
	
	/**
	 * 数据导入Excel的操作
	 */
	public String interExcel(){
		//获取所有的表中数据
		list = userService.getAllUser();
		//EXCEL文件路径
		String s = "D:/test.xls";
		ExcelOpt eop = new ExcelOpt();
		//数据导入Excel操作
		eop.a(s, list);
		return SUCCESS;
	}
	
	/**
	 * Excel导入到Oracle数据库表
	 */
	public String  goExcelToOracle(){
		GoToOracle go = new GoToOracle();
		String path="D:/test01.xls";
		List<String> l = new ArrayList<String>();
		l = go.insert(path);
		String[] st ;
		User user = new User();
		for(int i=0;i<l.size();i++){
			String str = l.get(i);
			st = str.split(",");
			user.setId(Integer.parseInt(st[0]));
			user.setUserName(st[1]);
			user.setPassword(st[2]);
			userService.insertUser(user);
		}
		return SUCCESS;
	}

}

13.tools

package com.daizhaoyun.tools;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.daizhaoyun.dto.User;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * @author daizhaoyun
 *  创建一个excel
 */
public class ExcelOpt{
	/**
	 * 生成一个Excel文件 jxl
	 */
	public void a(String fileName,List<User> list) {
		WritableWorkbook wwb = null;
		try {
			// 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
			wwb = Workbook.createWorkbook(new File(fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (wwb != null) {
			// 创建一个可写入的工作表
			// Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
			WritableSheet ws = wwb.createSheet("用户信息表", 0);
            Label label1 = new Label(1, 0, "ID");
            Label label2 = new Label(2, 0, "姓名");
            Label label3 = new Label(3, 0, "密码");
            try {
            	// 下面开始添加单元格
				ws.addCell(label1);
				ws.addCell(label2);
				ws.addCell(label3);
			} catch (RowsExceededException e1) {
				e1.printStackTrace();
			} catch (WriteException e1) {
				e1.printStackTrace();
			}
			// 下面开始添加单元格
			for (int i = 0; i < list.size(); i++) {
					Label label4 = new Label(1, i+1,list.get(i).getId().toString());
					Label label5 = new Label(2, i+1,list.get(i).getUserName());
					Label label6 = new Label(3, i+1,list.get(i).getPassword());
					// 这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
					/*Label labelC = new Label(j, i, "这是第" + (i + 1) + "行,第"
							+ (j + 1) + "列");*/
					try {
						// 将生成的单元格添加到工作表中
						ws.addCell(label4);
						ws.addCell(label5);
						ws.addCell(label6);
					} catch (RowsExceededException e) {
						e.printStackTrace();
					} catch (WriteException e) {
						e.printStackTrace();
					}
			}
			try {
				// 从内存中写入文件中
				wwb.write();
				// 关闭资源,释放内存
				wwb.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (WriteException e) {
				e.printStackTrace();
			}
		}
	}
	
}
?
package com.daizhaoyun.tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class GoToOracle {

	public List<String> insert(String path) {
		List<String> list = new ArrayList<String>();
		File file = new File(path);
		// 创建新的Excel 工作簿
		Workbook rwb = null;
		try {
			rwb = Workbook.getWorkbook(file);
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 得到工作簿中的第一个表索引即为excel下的sheet1,sheet2,sheet3...
		Sheet sheet = rwb.getSheets()[0];
		int rsColumns = sheet.getColumns();// 列数
		int rsRows = sheet.getRows();// 行数
		String simNumber = "";// 每个单元格中的数据

		String str = "";// 拼接要插入的列
	
		for (int i = 1; i < rsRows; i++) {
			for (int j = 0; j < rsColumns; j++) {
				Cell cell = sheet.getCell(j, i);
				simNumber = cell.getContents();
				if(j == rsColumns - 1){
					str += simNumber;
				}else{
					str += simNumber + ",";
				}
			}
			list.add(str);
			str = "";
		}
		return list;
	}

}
?

14.通过http://localhost:8080/excel/ getAllUser.action访问

  相关解决方案