批量导入用户信息
批量导入通常是将指定格式的excel或word文件上传到服务器,服务器读取上传的文件内容,将文件内容全部读取到数据库的过程。
此案例包括:文件下载、文件上传、EXCEL文件解析、将解析后的数据存入数据库。
操作步骤:
一、预备工作
0、引入包
文件上传:commons-fileupload-1.2.2.jar、commons-io-2.1.jar
文件下载:不需要JAR包支持
XLS文件解析:poi-3.7-20101029.jar
1、建表users
create table users(
id int primary key auto_increment,
name varchar(20) not null,
password varchar(32) not null,
sex varchar(2) not null,
birthday date not null,
hobby varchar(50) not null,
telephone varchar(15) not null,
address varchar(50) not null,
type int not null -- 1 admin 2 common user
);
插入测试数据:
insert into users values(1,'admin','202CB962AC59075B964B07152D234B70','男',
'1980-1-1','体育,旅游','13953311099','山东淄博',1);
insert into users values(2,'abc','202CB962AC59075B964B07152D234B70','女',
'1990-1-1','体育,音乐','1895330000','山东济南',2);
效果如下:
2、建立相应的JavaBean:
package cn.sdut.po;
public class User {
private int id;
private String name;
private String password;
private String sex;
private String birthday;
private String hobby;
private String telephone;
private String address;
private int type;
public User() {
super();
}
public User(int id, String name, String password, String sex,
String birthday, String hobby, String telephone, String address,
int type) {
super();
this.id = id;
this.name = name;
this.password = password;
this.sex = sex;
this.birthday = birthday;
this.hobby = hobby;
this.telephone = telephone;
this.address = address;
this.type = type;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password
+ ", sex=" + sex + ", birthday=" + birthday + ", hobby="
+ hobby + ", telephone=" + telephone + ", address=" + address
+ ", type=" + type + "]";
}
}
如果要进行批量导入,需要给用户提供一个模板供下载,user.xls(将其放置于WebRoot/excel/user.xls)
要在WebRoot下创建一个目录 excel,存放excel模板user.xls.
文件内容为:
序号 | 姓名 | 密码 | 性别 | 出生年月 | 爱好 | 联系方式 | 地址 | 用户类型(1-管理员 2-普通用户) |
---|---|---|---|---|---|---|---|---|
1 | 李华 | 6666 | 女 | 1977-3-3 | 音乐;美术 | 196852452 | 北京朝阳 | 2 |
注意:数据类型与数据库中的数据类型相匹配。需要特别注意数据的类型与日期类型的格式,见下图。