任务:
- 把存储在在Excel中的多条User类数据导入到目标数据库
- 把存储在在数据库中的多条User类数据导出到Excel表格
准备阶段:
- 配置了Mysql数据库
- 编译器导入了 jxl.jar 包,Excel表格处理包
- 编译器导入了 sql.jar 包,Mysql包
全部代码如下:
JavaBean类(User类):
package sample;
/**
* User账号类
*/
public class User {
private String userName;
private String password;
private String sex;
private String address;
private String tel;
private int flowerSum;
private String time;
public User(){
}
public User(String userName,String password){
this.userName = userName;
this.password = password;
}
public User(String userName,String password,String sex,String address,String tel,int flowerSum,String time){
this(userName, password);
this.sex = sex;
this.address = address;
this.tel = tel;
this.flowerSum = flowerSum;
this.time =time;
}
//setter和getter方法,要是没写无法读入tableView
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getFlowerSum() {
return flowerSum;
}
public void setFlowerSum(int flowerSum) {
this.flowerSum = flowerSum;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", tel='" + tel + '\'' +
", flowerSum=" + flowerSum +
", time='" + time + '\'' +
'}';
}
}
数据库工具类:
作用:连接数据库,对数据库进行增删改查
package sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import static java.sql.DriverManager.getConnection;
/**
* 数据库工具类
* @author Administrator
*
*/
public class Connectionlain {
/*String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://127.0.0.1;DatabaseName=test";*/
//驱动
//String driver = "com.mysql.jdbc.Driver";
String driver = "com.mysql.cj.jdbc.Driver";
// 数据库的位置,url是统一资源定位符,Java是我的目标数据库名,仅需修改这就可以了
String url = "jdbc:mysql://127.0.0.1:3306/java?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8";
Connection con = null;
ResultSet res = null;
public void DataBase() {
try {
Class.forName(driver);
con = getConnection(url, "root", "520");
} 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++) {
//把str[i]设为第i+1个数据
//sql语句没有第0个数据,1开始
pst.setString(i + 1, str[i]);
}
}
//PreparedStatement接口提供了三种执行 SQL 语句的方法:
//executeQuery、executeUpdate 和 execute
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();
}
return a;
}
}
User类的服务类:
作用:从数据库中获取User数据,从Excel中获取User数据
import jxl.Sheet;
import jxl.Workbook;
import sample.User;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* User类的数据服务
* @author Administrator
*
*/
public class UserService {
/**
* 获取数据库中所有的数据
* @return
*/
public static List<User> getAllByDb(String sqlname){
List<User> list=new ArrayList<User>();
try {
Connectionlain con = new Connectionlain();
String sql="select * from "+sqlname;
ResultSet rs= con.Search(sql, null);
while (rs.next()) {
String userName=rs.getString("userName");
String password=rs.getString("password");
String sex =rs.getString("sex");
String address = rs.getString("address");
String tel =rs.getString("tel");
int flowerSum = rs.getInt("flowerSum");
String time = rs.getString("time");
//System.out.println(id+" "+name+" "+sex+ " "+num);
//把当前数据插入集合,作为一条数据
list.add(new User(userName, password,sex,address,tel,flowerSum,time));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 获取EXCEL表格中所有的数据
* @param file 文件完整路径
* @return
*/
public static List<User> getAllByExcel(String file){
List<User> list=new ArrayList<User>();
try {
//打开工作簿
Workbook rwb=Workbook.getWorkbook(new File(file));
//选择目标工作表为:Sheet1
Sheet rs=rwb.getSheet(0);
int clos=rs.getColumns();//得到所有的列
int rows=rs.getRows();//得到所有的行
//System.out.println(clos+" rows:"+rows);
for (int i = 2; i < rows; i++) {
for (int j = 0; j < clos; j++) {
//第一个是列数,第二个是行数
String userName = rs.getCell(j++, i).getContents();//默认最左边编号也算一列 所以这里得j++
String password = rs.getCell(j++, i).getContents();
String sex =rs.getCell(j++, i).getContents();
String address =rs.getCell(j++, i).getContents();
String tel = rs.getCell(j++,i).getContents();
String flowerSum = rs.getCell(j++,i).getContents();
String time = rs.getCell(j++,i).getContents();
list.add(new User(userName,password,sex,address,tel,Integer.valueOf(flowerSum),time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
导入到数据库测试类
作用:将获取到的User数据导入目标数据库
import sample.Sale;
import sample.User;
import java.util.List;
/**
* 导入Excel数据
*/
public class TestExcelToDb{
public static void main(String[] args){
userExcel();
}
private static void userExcel() {
//得到目标Excel中所有的数据
List<User> listExcel = UserService.getAllByExcel("C:\\Users\\Administrator\\IdeaProjects\\untitled2\\src\\sample\\记录表.xls");
//连接数据库
Connectionlain con = new Connectionlain();
//遍历集合,依次导入数据进数据库
for (User u : listExcel) {
//编写SQL语句,列属性要和数据对上,否则导入会出错
String sql = "insert into flowerUser (userName,password,sex,address,tel,flowerSum,time) values(?,?,?,?,?,?,?)";
//需要插入的数据
String[] str = new String[]{
u.getUserName(),u.getPassword(),u.getSex(), u.getAddress(), u.getTel(),u.getFlowerSum()+"",u.getTime()};
con.AddU(sql, str);
}
}
导出到Excel测试类
作用:将获取到的User数据导出Excel表
package sql;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import sample.Flower;
import sample.Sale;
import sample.User;
import java.io.File;
import java.util.List;
/**
* Excel导表类
*/
public class TestDbToExcel {
public static void main(String[] args) {
() {
try {
WritableWorkbook wwb = null;
// 创建可写入的Excel工作簿
String fileName = "C:\\Users\\Administrator\\IdeaProjects\\untitled2\\src\\sample\\记录表.xls";
File file=new File(fileName);
//判断文件是否存在
if (!file.exists()) {
file.createNewFile();
}
//以fileName为文件名来创建一个Workbook
wwb = Workbook.createWorkbook(file);
//导出数据库flowerUser表中所有的数据
String sql=null;
sql = "flowerUser";
userExcel(sql,wwb);
//写进文档
wwb.write();
// 关闭Excel工作簿对象
wwb.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void userExcel(String sql,WritableWorkbook wwb) throws WriteException {
// 创建工作表sheet1为用户表
WritableSheet ws = wwb.createSheet("用户表", 0);
//从数据库中获取flowerUser的所有的数据
List<User> list= UserService.getAllByDb(sql);
//要插入到的Excel表格的行号(表头),默认从0开始
Label labelName= new Label(0, 0, "userName");
Label labelPassword= new Label(1, 0, "password");
Label labelSex= new Label(2, 0, "sex");
Label labelTel= new Label(3, 0, "tel");
Label labelAddress= new Label(4, 0, "address");
Label labelSum= new Label(5, 0, "flowerSum");
Label labelTime= new Label(6, 0, "time");
ws.addCell(labelName);
ws.addCell(labelPassword);
ws.addCell(labelSex);
ws.addCell(labelTel);
ws.addCell(labelAddress);
ws.addCell(labelSum);
ws.addCell(labelTime);
//逐行插入数据
//A1-B1-C1-D1....为一行
for (int i = 0; i < list.size(); i++) {
Label labelName_i= new Label(0, i+1, list.get(i).getUserName());
Label labelPassword_i= new Label(1, i+1, list.get(i).getPassword());
Label labelSex_i= new Label(2, i+1, list.get(i).getSex());
Label labelTel_i= new Label(3, i+1, list.get(i).getTel());
Label labelAddress_i= new Label(4, i+1, list.get(i).getAddress());
Label labelSum_i= new Label(5, i+1, list.get(i).getFlowerSum()+"");
Label labelTime_i= new Label(6, i+1, list.get(i).getTime());
ws.addCell(labelName_i);
ws.addCell(labelPassword_i);
ws.addCell(labelSex_i);
ws.addCell(labelTel_i);
ws.addCell(labelAddress_i);
ws.addCell(labelSum_i);
ws.addCell(labelTime_i);
}
}
}
代码执行效果:
Excel表:
数据库中的flowerUser表: