java Excel导入
以导入用户为例子
1、页面:HTML
//加载导入文件。
<input type="file" name="filePath" id="filePath" title="Excel用户导入" style="border:1px solid #666666;"/>
//开始导入按钮。
<yd:purvBtn value="Excel用户导入" onClick="ImportExcel();" keyWord="user!ImportExcel" style="width:120"></yd:purvBtn> //yd类型c标签
2、页面:js
//如果系统默认为get提交,就要添加如下方法。
function post(url,params){
var temp = document.createElement("form");
temp.action = url;
temp.method = "post";
temp.style.display = "none";
for(var x in params){
var opt = document.createElement("input");
opt.name = x;
opt.value = params[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
temp.submit();
return temp;
}
function ImportExcel(){
var filename= document.getElementById("filePath").value;
filename=filename.replace(/\\/g,'@'); // 将 \ 符号替换为@(如果是post提交就不必了)
if(!filename){
alert("请选择Excel文件");
}else{
// post提交到action url地址。
post('${pageContext.request.contextPath}/user!ImportExcel.action',{filename:filename});
}
}
3、控制器:action (SSH框架)
public String ImportExcel() throws UnsupportedEncodingException{
String fileName= getRequest().getParameter("filename");
//String fileName=new String(str1.getBytes("ISO-8859-1"),"utf-8"); //转码UTF8
String str2 = fileName.substring(fileName.length()-3, fileName.length());
//简单判断后缀是否为xls或xlsx的文件。
if(fileName.contains(".")){
if(str2.equals("xls") || str2.equals("lsx")){
}else{
getRequest().setAttribute("success","no");
return LIST;
}
}
//得到表格中所有的数据
List<User> listExcel=getExcel.getUserExcel(fileName); //调用getExcel工具类 的getUserExcel方法。
DBhepler db=new DBhepler(); //调用数据库操作类DBhepler
for (User user : listExcel) {
String id=user.getId();
if (!getExcel.isUserExist(id)) {
//不存在就添加
String sql="insert into user(id,dept_Id,name,password) values(?,?,?,?)";
String[] str=new String[]{user.getId(),user.getDeptId(),user.getName(),user.getPassword()};
db.AddU(sql, str);
}else {
//存在就更新
String sql="update user set dept_Id=?,name=?,password=? where id=?";
String[] str=new String[]{user.getDeptId(),user.getName(),user.getPassword(),user.getId()};
db.AddU(sql, str);
}
}
getRequest().setAttribute("success","success");
return LIST;
}
4、数据库操作类:
public class DBhepler {
//oracle数据库 (其他数据库的 driver url 应该不一样)
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:wuzhDB";
Connection con = null;
ResultSet res = null;
public void DataBase() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, "admin", "123456");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("装载 JDBC/ODBC 驱动程序失败。" );
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.err.println("无法连接数据库" );
e.printStackTrace();
}
}
// 查询
public ResultSet Search(String sql, String str[]) {
DataBase();
try {
PreparedStatement pst =con.prepareStatement(sql);
if (str != null) {
for (int i = 0; i < str.length; i++) {
pst.setString(i + 1, str[i]);
}
}
res = pst.executeQuery();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
// 增删修改
public int AddU(String sql, String str[]) {
int a = 0;
DataBase();
try {
PreparedStatement pst = con.prepareStatement(sql);
if (str != null) {
for (int i = 0; i < str.length; i++) {
pst.setString(i + 1, str[i]);
}
}
a = pst.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("更新行数:"+a);
return a;
}
}
5、getExcel类下的getUserExcel方法:
// 从Excel文件导入用户到List<User>
public static List<User> getUserExcel(String file){
file=file.replaceAll("@","\\\\"); // 把@符号换回 \ 符号 ,如果前面在js上没注释掉 filename=filename.replace(/\\/g,'@');
List<User> list=new ArrayList<User>();
try {
Workbook rwb=Workbook.getWorkbook(new File(file));
Sheet rs=rwb.getSheet("Sheet1");//或者rwb.getSheet(0)
int clos=rs.getColumns();//得到所有的列
int rows=rs.getRows();//得到所有的行
System.out.println(clos+" rows:"+rows);
for (int i = 1; i < rows; i++) {
for (int j = 0; j < clos; j++) {
//第一个是列数,第二个是行数
String id = rs.getCell(j++, i).getContents();//默认最左边编号也算一列 所以这里得j++
String dept_Id = rs.getCell(j++, i).getContents();
String name = rs.getCell(j++, i).getContents();
String password = rs.getCell(j++, i).getContents();
list.add(new User(id,dept_Id,no,name,password));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
6、getExcel类下的isUserExist方法:
//通过Id判断用户是否存在
public static boolean isUserExist(String id){
try {
DBhepler db=new DBhepler();
ResultSet rs=db.Search("select * from user where id=?", new String[]{id+""});
if (rs.next()) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
浙公网安备 33010602011771号